如何从子类访问java中超类的受保护字段?
我想从Java中的子类访问超类的受保护字段:如何从子类访问java中超类的受保护字段?,java,inheritance,Java,Inheritance,我想从Java中的子类访问超类的受保护字段: Class Super { protected int field; // field set to a value when calling constructor } Class B extends Super { // field of super class is set to value when calling // constructor } Class C extends Supe
Class Super {
protected int field; // field set to a value when calling constructor
}
Class B extends Super { // field of super class is set to value when calling
// constructor
}
Class C extends Super { // same here
}
B b = new B();
C c = new C();
b.super.field ?
类可以直接访问该字段,就像它是自己的字段一样。关键是执行访问的代码必须在派生类本身的代码中,而不是在使用派生类的代码中:
class B extends Super {
...
int getSuperField() {
return field;
}
}
类可以直接访问该字段,就像它是自己的字段一样。关键是执行访问的代码必须在派生类本身的代码中,而不是在使用派生类的代码中:
class B extends Super {
...
int getSuperField() {
return field;
}
}
在Super或B中,创建一个getter方法:
public int getField() {
return field;
}
然后你可以做:
B b = new B();
int field = b.getField();
在Super或B中,创建一个getter方法:
public int getField() {
return field;
}
然后你可以做:
B b = new B();
int field = b.getField();
不允许访问声明和扩展类主体之外的受保护字段 看这里 对象的受保护成员或构造函数可以从包的外部访问,在包中它只能由负责该对象实现的代码声明
解决方案是使用setter/getter或公开任何答案。不允许访问声明和扩展类主体之外的受保护字段 看这里 对象的受保护成员或构造函数可以从包的外部访问,在包中它只能由负责该对象实现的代码声明
解决方案是使用setter/getter或公开任何答案。受保护的修饰符允许子类直接访问超类成员 但是应该在子类内部或从同一个包中进行访问 例如:
package A;
public class Superclass{
protected String name;
protected int age;
}
package B;
import A.*;
public class LowerClass extends SuperClass{
public static void main(String args[]){
LowerClass lc = new LowerClass();
System.out.println("Name is: " + lc.name);
System.out.println("Age is: " + lc.age);
}
}
从Javadoc:
受保护修饰符指定成员只能在其自己的包内访问,就像使用包私有一样,并且只能由另一个包中其类的子类访问。受保护修饰符允许子类直接访问超类成员 但是应该在子类内部或从同一个包中进行访问 例如:
package A;
public class Superclass{
protected String name;
protected int age;
}
package B;
import A.*;
public class LowerClass extends SuperClass{
public static void main(String args[]){
LowerClass lc = new LowerClass();
System.out.println("Name is: " + lc.name);
System.out.println("Age is: " + lc.age);
}
}
从Javadoc:
protected修饰符指定成员只能在其自己的包内访问,就像使用包private一样,此外,还可以通过另一个包中其类的子类访问该成员