Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 667
user3880721 Avatar asked Aug 18 '14 18:08

user3880721


People also ask

Can protected members be accessed outside the package?

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.

Can we access protected member outside the package in subclass?

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.

Which fields are accessible from outside the package?

Outside the package, the member j is accessible to any class, whereas the member k is only accessible to subclasses of MyClass. The field i has package accessibility, and is only accessible by classes inside the package. The field j has public accessibility, and is accessible from anywhere.


2 Answers

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.

like image 125
Alex Kleiman Avatar answered Sep 19 '22 16:09

Alex Kleiman


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.

like image 44
M A Avatar answered Sep 19 '22 16:09

M A