Possible Duplicate:
Java inner class and static nested class
An instance of a static inner class cannot access the instance members of its enclosing class, whereas an instance of a non-static inner class can. This is what i mean by syntactic difference. Because whether declaring an inner class to be static determines whether the syntax of your program is correct.
But is there any other difference that's not part of the Java syntax? Let's say class A is a top-level class, and class B is an inner class of A. If I'm not going to access the instance members of A within B, then I should declare B to be static. But since i'm not required to, i could declare B to be non-static and there would be no compilation error. So in this case, is there any difference, probably in the generated bytecode, or any runtime difference?
Thanks!
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
The static method uses compile-time or early binding. The non-static method uses runtime or dynamic binding. The static method cannot be overridden because of early binding. The non-static method can be overridden because of runtime binding.
1) First and most important difference between Inner class and nested static class is that Inner class require instance of outer class for initialization and they are always associated with instance of enclosing class. On the other hand nested static class is not associated with any instance of enclosing class.
A non-static method does not have the keyword static before the name of the method. A non-static method belongs to an object of the class and you have to create an instance of the class to access it. Non-static methods can access any static method and any static variable without creating an instance of the class.
The difference is bigger than that. static
inner classes can be created from outside the class
, without having an instance of the class, non-static ones cannot.
The fact that you can access enclosing class members is a result of this, because a static
inner class is not bound to an instance of the enclosing class, but a non-static
one is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With