以下产生错误:
class A {
static int apple = 5;
static class StaticNestedSubClassOfA {
//...
}
}
class Test {
public static void main(String str[]) {
A.StaticNestedSubClassOfA b = new A.StaticNestedSubClassOfA();
System.out.println("Apple: " + b.apple);
}
}
错误:
Test.java:14: error: cannot find symbol System.out.println("Apple: " + b.apple); ^ symbol: variable apple location: variable b of type StaticNestedSubClassOfA 1 error
但是StaticNestedSubClassOfA
无法访问静态变量apple
吗? (我想这并不意味着从StaticNestedSubClassOfA
产生的对象可以访问apple
到他们的实例?)
答案 0 :(得分:0)
您正在访问课程A.apple
中的Test
这无法正常工作。
编译A时,它不知道如何从所有可能的类访问它,并且无法生成使其工作所需的访问方法。
JVM不允许访问类之间的私有成员。相反,javac
编译器在外部类下的同一java
类文件中添加访问方法。这就是为什么有时候在调用堆栈中看到像access$200
这样的方法的原因。类通过生成的访问器方法从另一个类访问私有成员。如果你在一个不相关的课程中,你不能访问私人领域,javac也不能为你实现这样做而不事先创建所有可能的访问者(它不会这样做)
答案 1 :(得分:0)
这是我能想到的唯一方法。
public class Outer
{
private static int apples = 5;
public static class Inner {
public int getApples() { return Outer.apples; }
}
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
System.out.println( inner.getApples() );
}
}
就运行时而言,Outer
和Inner
是两个独立的类。它们嵌套的想法是由编译器维护的虚构。因此,在运行时,编译器无法使用Outer
访问Inner
。
因为它们共享一个范围,所以编译器 允许Inner
访问Outer
中的私有方法和字段。但这是编译器可以在没有运行时帮助的情况下实现的技巧。其他技巧,比如你试图直接按名称访问字段,是不可能的。