I am trying to figured out how protected access modifier works between packages inheritance in Java.
I have 2 sample packages p1 and p2. In p1 there is a class A1 with a protected access instance variable named protectedMember and another class B1 that simply extends A1.
In p2 I have a class A2 that also extends A1. Obviously in A2 I will have a direct access to the protected member of its parent (class A1) which is fine and out of my question.
However if I create a method in A2 that rises up an instance of A1 or its child B1 - then I CANNOT REACH the protected member of this instance. Why ? Protected members unlike default are accessible to package and outside package classes that extends the class.
So why in "multiple package" inheritance I can reach parent's protected member directly, but non with an instance.
Please do not response "you must do it in parent's package" - I see I must.
I want to know WHY ?
package p2;
import p1.A1;
import p1.B1;
public class A2 extends A1 {
// please note - multi package inheritance
public void test (){
/*
with non of the instances below I can reach the protected member in A1
*/
A1 a1 = new A1();
B1 b1 = new B1();
}
}