Java – inherited protected member behavior

I have some questions about the protection identifier In the first chapter of K. Sierra's sun certified java programmer learning guide, I found the following information:

"Once a subclass - inherits a protected member outside the package, the member (inherited by the subclass) is private to any code outside the subclass, except the subclass of the subclass."

I have provided sample code that reflects the above statement, which is absolutely clear to me

// Parent class
package package1;

import package2.Child;
public class Parent {

    protected int i = 5;

}

// Child class
package package2;

import package1.Parent;

public class Child extends Parent {

    // variable 'i' inherited

}


package package2;

public class Neighbour {

    public void protectedTesting(){
        Child child = new Child();
        System.out.println(child.i); // no access
    }
}

I've started trying and made some small changes - moving neighbor to package 1 And I can access the "I" variable, which is a little surprising to me because it does not conform to the statement "private to any code other than subclasses"

Changed neighbor class:

package package1;

import package2.Child;

public class Neighbour {

    public void protectedTesting(){
        Child child = new Child();
        System.out.println(child.i); // access!
    }
}

Please clarify to me thank you.

Solution

In short, protected is package private and subclass visible Even JLS is vague about this (JLS § 6.6.2):

It specifies that only subclasses can access protected members outside the package This means that you can also access variables in the package Its wording is poor, but the real thing is that protected members have package level visibility and subclass level visibility

You can also see:

>This related question > java trail for access control

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>