Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when to use static inner class or instance inner class? [duplicate]

Tags:

java

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();

    }

}
like image 208
CrawlingKid Avatar asked Dec 11 '22 15:12

CrawlingKid


2 Answers

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.

like image 179
Brigham Avatar answered Jan 11 '23 23:01

Brigham


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.

like image 34
RiaD Avatar answered Jan 12 '23 01:01

RiaD