Jag*_*uar 16 java access-modifiers
我无法理解为什么这段代码无法编译:
class A {
public static void main(String[] args) {
System.out.println("hi");
}
}
private class B {
int a;
}
Run Code Online (Sandbox Code Playgroud)
我将内容保存在一个名为的文件中A.java- 我收到一个错误:
modifier private not allowed here // where I have defined class B
Run Code Online (Sandbox Code Playgroud)
当我尝试B作为私有和受保护时,会发生这种情况.有人可以解释一下这背后的原因吗?
谢谢 !
And*_*s_D 21
从Java语言规范:
访问修饰符protected和private仅适用于直接封闭类声明中的成员类
所以是的,私有和受保护的修饰符不允许用于顶级类声明.
顶级类可以是公共的或没有,而private并protected不允许.如果该类声明为public,则可以从任何包中引用它.否则,它只能从同一个包(名称空间)引用.
私有顶级类没有多大意义,因为它无法从任何类引用.根据定义,它将无法使用.private成员类可以使一个类仅适用于它的封闭类.
A protected member class can be referred to from (1) any class of the same package and from (2) any subclass of the enclosing class. Mapping this concept to top level classes is difficult. The first case is covered by top level class with no access modifiers. The second case is not applicable for top level classes, because there is no enclosing class or something else from a different package with a special relation to this class (like a subclass). Because of this I think, protected is not allowed because it's underlying concept is not applicable for top level classes.
| 归档时间: |
|
| 查看次数: |
24912 次 |
| 最近记录: |