Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
静态嵌套类通过对象引用访问实例变量的Java示例_Java_Static_Inner Classes - Fatal编程技术网

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

静态嵌套类通过对象引用访问实例变量的Java示例,java,static,inner-classes,Java,Static,Inner Classes,根据Java教程,静态嵌套类不能直接引用其封闭类中定义的实例变量或方法,但只能通过对象引用使用它们。有人能给我举个例子吗?我是否需要在静态嵌套类中创建封闭类的实例,然后引用该实例的实例变量/方法?考虑一个名为Main的类,该类有一个私有字段值,给定一个名为nested的静态嵌套类,如果没有Main实例,则无法访问该值。像 请注意,该值是私有的,但嵌套的可以通过引用m访问它 public class Main { private final int value = 100; st

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

考虑一个名为Main的类,该类有一个私有字段值,给定一个名为nested的静态嵌套类,如果没有Main实例,则无法访问该值。像

请注意,该值是私有的,但嵌套的可以通过引用m访问它

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.
        }
    }
}
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