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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With