Ex15.java
import utils.A;
public class Ex15 extends A{
public static void main(String[] args){
A a = new A();
a.print("Test");
}
}
**utils/A.java**
package utils;
public class A {
public A(){
System.out.println("A created");
}
protected void print(String s){
System.out.println(s);
}
}
tree
michael@michael:~/Downloads/thinking_in_java/Reusing_Classes/Ex15$ tree
.
├── Ex15.class
├── Ex15.java
└── utils
├── A.class
└── A.java
Compilation:
michael@michael:~/Downloads/thinking_in_java/Reusing_Classes/Ex15$ javac Ex15.java
Ex15.java:6: error: print(String) has protected access in A
a.print("Test");
^
1 error
Documentation
https://docs.oracle.com/javase/specs/jls/se14/html/jls-6.html#jls-6.6.2.1
Quotation:
Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.
A subclass S is regarded as being responsible for the implementation of objects of class C. Depending on C's accessibility, S may be declared in the same package as C, or in different package of the same module as C, or in a package of a different module entirely.
Problem
Class Ex15 is a subclass of A. It is in a different package (in a default one, but definitely not in "utils"). Access to the protected method is within the body of the subclass. I didn't expect a compilation error.
Could you clarify why this error occurs and how to make the code compile.