通过对象引用访问实例变量的静态嵌套类的Java示例

时间:2017-05-18 00:56:31

标签: java static inner-classes

根据Java Tutorial,静态嵌套类不能直接引用其封闭类中定义的实例变量或方法,但它只能通过对象引用来使用它们。有人能举个例子吗?我是否需要在静态嵌套类中创建封闭类的实例,然后引用实例的实例变量/方法?

2 个答案:

答案 0 :(得分:0)

考虑一个名为Main且带有private字段value的类,给定一个名为static的{​​{1}}嵌套类,如果没有Nested,则无法访问value Main的一个实例。喜欢,

public class Main {
    private final int value = 100;

    static class Nested {
        static void say(Main m) {
            System.out.println(m.value); // <-- without m, this is illegal.
        }
    }
}

请注意,value privateNested 可以访问它(通过参考 m)。

答案 1 :(得分:0)

class A {
  public void foo() {...}
  public static class B {
    public void bar() {
      foo(); // you can't do this, because B does not have a containing A. 
        //If B were not static, it would be fine
     }
  }
}

// somewhere else 

A.B val = new A.B(); // you can't do this if B is not static