Reputation: 2319
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 ?
Upvotes: 2
Views: 6737
Reputation: 21
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.
Upvotes: 2
Reputation: 37584
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.
Upvotes: 1
Reputation: 604
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();
Upvotes: 1
Reputation: 726479
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;
}
}
Upvotes: 4