【问题标题】:Java example of a static nested class accessing an instance variable through an object reference [duplicate]通过对象引用访问实例变量的静态嵌套类的 Java 示例 [重复]
【发布时间】:2017-05-18 00:56:30
【问题描述】:

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

【问题讨论】:

    标签: java static inner-classes


    【解决方案1】:

    考虑一个名为Main 的类和一个private 字段value,给定一个名为static 的嵌套类Nested,如果没有Main 的实例,您将无法访问value。喜欢,

    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)。

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

      • 我知道你不能这样做,但不应该这样做吗? A a = new A(); A.B b = new a.B();其他静态成员可以通过这种方式访问​​。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多