我在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(); //
//UPDATED: Declaration is ok
MyClass.protectedInnerClass y; //
//UPDATED: Only when instantiated is not allowed, why?
y = x.new protectedInnerClass(); //
}
}
请参阅Java文档:
“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.”
为什么我不能实例化如上所示的内部受保护类?
解决方法:
8.8.9. Default Constructor
… if the class is declared protected, then the default constructor is implicitly given the access modifier protected (07001); …
所以隐式声明的构造函数是:
protected class protectedInnerClass {
protected protectedInnerClass(){
super();
}
}
您的代码将无法编译,因为构造函数不可访问.
标签:java,inner-classes,subclass
来源: https://codeday.me/bug/20190714/1460378.html