简体   繁体   中英

Access control — protected members from outside the package

i've got the class P4 in the default package (i know using the default package is bad practice, but merely "for example" for now):

import temp.P2;

public class P4 extends P2 {

public void someMethod() {    
    P2 p2 = new P2();
//        p2.p2default();   // ERROR as expected
    p2.p2public();
    p2.p2protected();  // ERROR as not expected
}    

}

and class P2 in package temp

package temp;

public class P2 {

protected void p2protected() {    
...
}    

public void p2public() {    
...
}    

void p2default() {    
...
}    

}

From the access control mechanism , i'd expect P4 -- having extended P2 , should be able to see the protected member of its super class even from outside the package once it imported the namespace of that package.

What am i missing?

TIA.

The issue may be that you are not trying to inherit the p2protected() method, which you should be able to do, but rather to call p2protected() . You cannot call a protected method on a different object from a different package, even if you are extending the class. super.p2protected() should work, however.

You defined P2 p2 = new P2(); of type P2 and not P4 . If p2 were of type P4 it would have access to it since it is a subclass of P2 .

From the JLS :

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object .

In your code you are trying to access the protected member of another object.

public void someMethod() {    
    P2 p2 = new P2();

    p2.p2protected();  // doesn't work, because someMethod and p2.p2protected
                       // operate on different objects (this vs. p2) 

    p2protected (); // works, because someMethod and p2protected operate
                    // on the same object (this)
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM