An Understanding of Protected Access Control Modifiers in Java

Asked 1 years ago, Updated 1 years ago, 80 views

There is a class called A in package1 and a class called C in package2. Class C is a subclass of A.

A defined the instance field protectedInt:

protected int protectedInt = 1;

Class A:

package package1;

public class A {

    public int publicInt = 1;
    private int privateInt = 1;
    int defaultInt = 1;
    protected int protectedInt = 1;

}

C class:

package package2;
import package1.A;

public class C extends A{

    public void go(){
        //remember the import statement
        A a = new A();
        System.out.println(a.publicInt);
        System.out.println(a.protectedInt);

    }
}

The last line of the Eclip Seungseo C.go() method results in a red line and an error message stating that "A.protectedInt" is not visible. The definition of the "protected" access control indicator appears to be in conflict. This is an excerpt from the following Oracle documentation.

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Why is that?

java visibility protected access-modifiers

2022-09-21 21:30

1 Answers

Why is that?

I think I misunderstood the meaning of protected. You can access protected members declared in A within objects in the subclass of C or C. Learn more about protected access at section 6.6.2 of the JLS . Especially the bottom part.

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. In addition, if Id denotes an instance field or instance method, then:

So there is no error in the code of below:

C c = new C();
System.out.println(c.publicInt);
System.out.println(c.protectedInt);


2022-09-21 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.