gpt4 book ai didi

java - protected 内部类不能从另一个包的子类访问

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:29:46 24 4
gpt4 key购买 nike

我在 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 (§6.6); ...

所以隐式声明的构造函数是:

protected class protectedInnerClass {
protected protectedInnerClass(){
super();
}
}

您的代码无法编译,因为构造函数不可访问。

关于java - protected 内部类不能从另一个包的子类访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17610498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com