简体   繁体   English

从静态内部类访问外部类的静态变量

[英]Access Static variable of Outer class from Static Inner class

I'm learning about nested classes. 我正在学习嵌套类。 I just want to know why I'm not able to access a static variable of the outer class from a static inner class using an instance of it. 我只想知道为什么我无法使用其实例从静态内部类访问外部类的静态变量。

class MyListner {
    static String name = "StaticApple";
    String nonStaticName = "NonStaticApple";

    static class InnerMyListner {
        void display(){
            System.out.println("Static variable of outer class: " + name);
        }
    }

    private static final MyListner singleton = new MyListner();

    private MyListner() {

    };

    public static MyListner getInstance() {
        return singleton;
    }
}

public class Results{
    public static void main(String[] args) {
        MyListner.getInstance();

        MyListner.InnerMyListner innerclassO = new MyListner.InnerMyListner();
        innerclassO.display();  // This works
        String staticVariable = innerclassO.name;  // Why doesn't this work?
    }
}

You have to understand how class (es) works here. 您必须在这里了解class工作方式。 InnerMyListner class is an static nested class. InnerMyListner类是一个静态的嵌套类。

As with class methods and variables, a static nested class is associated with its outer class. 与类方法和变量一样,静态嵌套类与其外部类相关联。

While the static nested class cannot access the outer class' instance properties, it can access static properties (shared by all the instances), which are inside the visibility scope. 虽然静态嵌套类无法访问外部类的实例属性,但可以访问可见性范围内的静态属性(由所有实例共享)。

Inside Results you're out of the visibility scope for name . 在内部Results您不在name的可见范围内。
For a more in depth overview, see Java documentation 有关更深入的概述,请参见Java文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM