静态嵌套类(实例)是否可以访问外部静态变量?

时间:2015-11-16 23:38:19

标签: java

以下产生错误:

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 他们的实例?)

2 个答案:

答案 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() );
   }
}

就运行时而言,OuterInner是两个独立的类。它们嵌套的想法是由编译器维护的虚构。因此,在运行时,编译器无法使用Outer访问Inner

因为它们共享一个范围,所以编译器 允许Inner访问Outer中的私有方法和字段。但这是编译器可以在没有运行时帮助的情况下实现的技巧。其他技巧,比如你试图直接按名称访问字段,是不可能的。