I’m reading this Java SCJP book and I came across this:
The protected and default access control
levels are almost identical, but with one critical difference. A
default member may be accessed only if the class accessing the member
belongs to the same package, whereas a protected member can be
accessed (through inheritance) by a subclass even if the subclass is
in a different package.
So I decided to test out the protected point.
I have a super-class in a package
package scjp;
public class Token {
protected int age = 6; //This is the protected class-level variable.
public Token(String name){
this.name = name;
}
public Token(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
}
The I have a sub-class in another package;
package pack;
import scjp.Token;
public class son extends Token{
public static void main(String[] args) {
System.out.println(Token.age);
}
}
As you can see I’m trying to access the protected class-level integer variable age in the super-class.
But I get this error:
age has protected access in scjp.Token
at pack.son.main(son.java:11)
Java Result: 1
So, what’s going wrong?
You are trying to access a non static protected member of your super class with class reference..
will compile and work fine.