0

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();
    }

}
Georgi Velev
  • 166
  • 10
  • 1
    It's explained in detail [in the JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.6.2). Not sure that I could answer _why_ protected access has been designed this way though. – Dawood ibn Kareem Jun 12 '19 at 20:57

2 Answers2

0

Because it's possible to have an instance of A1 (A1 a1 = new A1()) even outside classes that extend it.

Let's say you have:

public class B2 {
  public void test() {
    A1 a1 = new A1();
  }
}

Obviously accessing protected fields of A1 should fail.

Šimon Kocúrek
  • 1,591
  • 1
  • 12
  • 22
0

Because it is a rule. Access to protected member or method declared in A1 or B1 from A2 is allowed only if object type is A2, not A1 or B1 instance. You can find further information here: https://docs.oracle.com/javase/specs/jls/se8/jls8.pdf

iperezmel78
  • 415
  • 5
  • 20