I am learning about access levels in java and I have created 3 classes:
In package my.inheritance
I have class A and class C
package my.inheritance;
public class A {
protected int a=15;
}
package my.inheritance;
public class C {
public static void main(String[] args)
{
A a = new A();
System.out.println(a.a);
}
}
And in another package called my.inheritance.test I have a class B trying to access protected field of int value a but the compiler complains for this!
package my.inheritance.test;
import my.inheritance.A;
public class B extends A{
public static void main(String[] args)
{
A a = new A();
int value = a.a;
System.out.println(value);
}
}
I was under the impression with protected you can access a member from a different class in a different package as long as you subclass it! Why the visibility error then ?
Every method can access protected fields of its own class, and all its parent classes. This does not include access to protected fields of another class, even if they have the corresponding base class in common.
So methods in class
Bcan access protected fields from objects of classB, even if they were declared inA, but not from some other object of classA.One could say that class
Binherits the protected members fromA, so now everyBhas those members as well. It doesn’t inherit access to the protected members ofAitself, so it cannot operate on protected members of anyAbut only on those ofB, even if they were inherited fromA.