I have the following code in Java:
package a;
public classs ClassInOtherPackage{
protected void protectedMethod(){}
protected class protectedInnerClass {}
}
package b;
import a.*;
public class MyClass extends ClassInOtherPackage{
public MyClass(){
MyClass x = new MyClass();
x.protectedMethod(); //<-- This one ok
//UPDATED: Declaration is ok
MyClass.protectedInnerClass y; //<-- This one ok
//UPDATED: Only when instantiated is not allowed, why?
y = x.new protectedInnerClass(); //<-- Not allow when instantiated.
}
}
Refer to the Java documentation:
"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."
Why can't I instantiate the inner protected class as shown above?
In JLS 8.8.9
8.8.9. Default Constructor
... if the class is declared
protected, then the default constructor is implicitly given the access modifierprotected(§6.6); ...
So the implicitly declared constructor is:
protected class protectedInnerClass {
protected protectedInnerClass(){
super();
}
}
You code won't compile because the constructer is inaccessible.
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