I have a class A with a protected member :
package p1;
public class A{
protected int number;
}
Now I've subclassed it in another package :
package p2;
public class B extends A{}
Now in the main class :
package p3;
public class Main{
public static void main(String[] args){
B b = new B();
System.out.println(b.number);
}
}
This executes perfectly. What is the visibility of protected members in subclass - do they become public ? Then I tried following which also didn't show any error:
System.out.println(new A().number);
After seeing this I've came to conclusion that I'm doing something really silly or misunderstood the use of protected
specifier. The way I learnt : protected
members can only be accessed within subclasses irrespective of packages and they remained in the same viasibilty. But the way I'm able to access the member number
like a public
variable even in the parent class.
Please help me understand what is happening here.
CodePudding user response:
Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
You can read more about this here