I know that this has been asked before in this forum but i will ask again since i don't see any good answer (so far).
Here it goes:
package a;
public class A{
protected int a;
}
package b;
public class B extends A{
}
package c;
public class C extends B{
public void accessField(){
A ancient = new A();
ancient.a = 2; //A - That wouldn't work.
a = 2; //B - That works.
}
}
Why clause A) won't work? What's the rational behind this restriction on superclass object ancient access in subclass C?
Thanks.
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.
Because protected is visible to the class itself (like private ) and its subclasses. It is not public. protected instance methods are visible to the class itself, and to instances of subclasses, but not to static methods in subclasses.
The protected members are inherited by the child classes and can access them as its own members. But we can't access these members using the reference of the parent class. We can access protected members only by using child class reference.
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.
Protected members can only be accessed outside of the same package if it's via inheritance - i.e. within the hierarchy.
So when you're creating another instance of A from a different package, that's not an inheritance relationship and it thus fails.
As always, this is covered in the JLS, 6.6.2:
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.
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