Reputation: 63
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?
}
}
Upvotes: 0
Views: 1691
Reputation: 21172
You have to understand how class
(es) works here.
InnerMyListner
class is an static nested class.
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
.
For a more in depth overview, see Java documentation
Upvotes: 1