How to access protected field of a super class in java from subclasses?

旧城冷巷雨未停 提交于 2020-01-15 11:30:07

问题


I want to access a protected field of a super-class from a sub-class in 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 Super { // same here

}
B b = new B();
C c = new C();
b.super.field ?

回答1:


The class can access the field directly, as if it were its own field. The catch is that the code doing the access must be in the code of the derived class itself, not in the code using the derived class:

class B extends Super {
    ...
    int getSuperField() {
        return field;
    }
}



回答2:


In either Super or B, create a getter method:

public int getField() {
    return field;
}

Then you can do:

B b = new B();
int field = b.getField();



回答3:


It's not allowed to access a protected field outside the body of the declaring and extending class.

See here 6.6.2 Access to a protected Member

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

The solution would be any of the answers with a setter/getter or making it public.




回答4:


The protected modifier allows a subclass to access the superclass members directly.

But the access should be made inside the subclass or from the same package.

Example:

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);   
  }  
}

From Javadoc:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.



来源:https://stackoverflow.com/questions/42760522/how-to-access-protected-field-of-a-super-class-in-java-from-subclasses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!