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 B
can access protected fields from objects of class B
, even if they were declared in A
, but not from some other object of class A
.
One could say that class B
inherits the protected members from A
, so now every B
has those members as well. It doesn't inherit access to the protected members of A
itself, so it cannot operate on protected members of any A
but only on those of B
, even if they were inherited from A
.
Try:
public class B extends A
{
public static void main(String[] args)
{
B a = new B();
int value = a.a;
System.out.println(value);
}
}
You can access a only if it is in the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With