Access control - protected elements from outside the package

I have a P4 class in the default package (I know that using the default package is bad practice, but just β€œfor example” at the moment):

 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 the temp package

 package temp; public class P2 { protected void p2protected() { ... } public void p2public() { ... } void p2default() { ... } } 

From the access control mechanism , I would expect P4 - with extended P2 should be able to see the protected member of my superclass even outside the package as soon as it imports the namespace of this package.

What am I missing?

TIA.

+6
source share
3 answers

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

+2
source

The problem may be that you are not trying to inherit the p2protected() method that you must execute, but rather call p2protected() . You cannot call the protected method on another object from another package, even if you extend the class. super.p2protected() should work, however.

+4
source

From JLS :

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

In your code, you are trying to access a 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) } 
+1
source

Source: https://habr.com/ru/post/973996/


All Articles