java – 不能从另一个包的子类访问受保护的内部类

我在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.
  }
}

请参阅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.”

为什么我不能实例化如上所示的内部受保护类?

最佳答案
JLS 8.8.9

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 – 不能从另一个包的子类访问受保护的内部类 - 代码日志