1

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.

Michael
  • 4,273
  • 3
  • 40
  • 69

2 Answers2

2

You're trying to invoke a method with a scope that you cannot see from that point. Even if your class is a subclass, it cannot access the method because it's not in its visibility. You can invoke private/protected method of the class Ext15, not the class A. A is still in another package.

Try to look here for a better explanation.

Fildor
  • 14,510
  • 4
  • 35
  • 67
sigur
  • 662
  • 6
  • 21
1

It's because you're calling at a.print("Text") not as a subclass. When you're creating a superclass like that it's like creating it any other class that is not a subclass.

protected you can access as the subclass like super.print("Text").

akcode
  • 76
  • 3