What is the difference between static and non-static nested class?
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.
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.
Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kinds of classes in Java, one is called a top-level class and the other is called a nested class.
Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.
An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"
A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:
Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.
And now to quote:
Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance.
A static nested class does not have access to the enclosing instance. It uses less space too.
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