I observed that static inner class can access all the static data members and member function of outer class. How does java do this?
class StaticClass{
static int x=10;
static void show() {
System.out.println("show");
}
public static void main(String[] args) {
InnerStatic i = new InnerStatic();
i.display();
}
static class InnerStatic {
static void display() {
System.out.println(x);
show();
}
}
}
Static members in Java are allocated on one-per-class basis. Since there is only one per-class item for any static member, Java knows where each one of them is at runtime.
Therefore, the only issue here becomes visibility of the item from the point of view of access control. Here, too, Java has no issues, because Java compiler knows from where each static item can be accessed.
In your example, InnerStatic.display
can access StaticClass.show
in the same way that StaticClass.main
can. In fact, any method in the same package as StaticClass
is allowed to do this:
StaticClass.show(); // this will compile from anywhere
The advantage of InnerStatic
is that the compiler knows of the "surrounding" class, so when it does not find InnerStatic.show
it continues looking, and finds the method in the StaticClass
.
A static
method can access the static
fields and methods of any other class unless access modifiers prevent it.
These are accessed in the same way that methods and fields are accessed in the same class.
In your example, inner/outer has nothing to do with it. Your fields and methods are all either public
or package-private (ie, have no visibility modifier), and would be accessible to any class that is in the same package.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.