在面向对象编程中,protected属性是一种访问修饰符,用于限制只有当前类及其子类可以访问该属性。如果想要获取另一个类中的protected属性,可以通过以下步骤进行操作:
下面是一个示例代码:
class ParentClass {
protected int protectedAttribute = 10;
}
class ChildClass extends ParentClass {
public int getProtectedAttribute() {
return protectedAttribute;
}
}
public class Main {
public static void main(String[] args) {
ChildClass child = new ChildClass();
int value = child.getProtectedAttribute();
System.out.println(value); // 输出:10
}
}
在上述示例中,ParentClass是一个父类,其中包含一个protected属性protectedAttribute。ChildClass是ParentClass的子类,通过继承关系,ChildClass可以直接访问父类的protected属性。在ChildClass中,通过创建ChildClass的实例child,并调用getProtectedAttribute()方法,就可以获取到父类中protectedAttribute的值。
需要注意的是,protected属性的访问权限仅限于当前类及其子类,如果在不同的包中,子类必须与父类在同一个包中才能访问protected属性。
领取专属 10元无门槛券
手把手带您无忧上云