Why do we make a class static in java?

29,094

Solution 1

class Outer {
    int a;
    class Inner {
        void test() {
            System.out.println(a);
        }
    }
}

Normally, an inner class may reference its owning class's fields, as you can see in the (pseudo) sample above. So an instance of Inner may access fields / methods / etc in Outer.

But this requires every Inner instance to have an Outer instance associated with it. So you cannot do

new Inner();

but instead must do

new Outer().new Inner();

In some cases this is not desirable - say you need to ensure that your Outer instances may get garbage collected, or that you need to make Inner instances independent of Outer. In that case you may change it to

static class Inner {

in which case now you may no longer reference "a" as before, but in exchange you don't need to have an instance of Outer at all to have instances of Inner.

Solution 2

Top-level classes can't be declared static, only nested classes can be:

class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
    class InnerClass {
        ...
    }
}

The difference is that:

  • 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 above is taken from the Java OO tutorial. You can read more here.

Solution 3

You cannot declare static classes. The only thing you can do is to declare static inner classes, which means that you do not need an instance of the outer class to access it.

Share:
29,094
Khawar Raza
Author by

Khawar Raza

I am working on Android applications for last 6 years and trying to have aligned vision, objectives, and goals to achieve win-win situation in every project.

Updated on November 12, 2020

Comments

  • Khawar Raza
    Khawar Raza over 3 years

    Possible Duplicate:
    Static nested class in Java, why?

    I know about the static fields in java. But don't know why we create a static class. Any idea?

  • aman
    aman over 12 years
    Keeping in mind that non static inner classes MUST be instantiated from within an outer classes instance, while static classes can be instantiated whenever. I guess those details are in your link?