我正在学习嵌套类。我只是想知道为什么我无法使用静态内部类的实例访问外部类的静态变量。
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?
}
}
最佳答案
您必须了解class
(es)在这里是如何工作的。
InnerMyListner
类是一个静态嵌套类。
As with class methods and variables, a static nested class is associated with its outer class.
虽然静态嵌套类无法访问外部类的实例属性,但它可以访问可见范围内的静态属性(由所有实例共享) .
在结果
内,您超出了name
的可见范围。
有关更深入的概述,请参阅Java documentation
关于java - 从静态内部类访问外部类的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616986/