I have a Java project with the following file structure:
src
└── A
├── P1.java
└── P2.java
P1.java
is inside package A
, while P2.java
is at the same level as A
.
Here is the code for P1.java
:
package A;
public class P1 {
public int a1;
protected int a2;
}
And here is the code for P2.java
:
import A.P1;
public class P2 extends P1 {
public static void main(String[] args) {
P1 p = new P1();
System.out.println(p.a1);
System.out.println(p.a2); // error?
}
}
When I run this, I get the following error:
java: a2 has protected access in A.P1
However, I recall that a protected variable should be accessible in a subclass, even if they are not in the same package.
Why is this happening? Since P2
is a subclass of P1
, it should be able to access a2
.