I have been studying about static inner class in java. But i am not clear whats the point of using static inner class or inner class.
class A{
static class B{
}
public static void main(String[] args) {
B b=new B();
}
}
or
class B{}
class A{
public static void main(String[] args) {
B b=new B();
}
}
Non-static inner classes have an automatic reference to their enclosing class. A static inner classes only relationship to its enclosing class is that you have to reference it via the enclosing class' name: EnclosingClass.StaticInnerClass
.
Non-static inner classes are good when you want to reference some of the data from the parent class.
A static inner class is good when you just want to associate the inner class with the enclosing class without dragging it along for the ride.
In other words, a non-static inner class can prevent the enclosing class from being garbage collected, since it has that reference, while a static inner class will never do that.
There is technical difference:
class A {
private static int x = 42; //the answer
public static class B {
int showX() {
return x; // only static class can it
}
}
}
But it isn't the main point. If class B
is used only by class A
it's good to make it inner because some classes in one package may want to have utility class with same name.
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