10

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?

Community
  • 1
  • 1
Khawar Raza
  • 15,870
  • 24
  • 70
  • 127
  • 3
    http://stackoverflow.com/questions/7370808/why-a-top-level-class-cannot-be-static-in-java/7370832#7370832 seems to answer this. – AKX Oct 21 '11 at 07:25

3 Answers3

20
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.

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
19

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    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? – Nico Oct 21 '11 at 07:29
1

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.

dwalldorf
  • 1,379
  • 3
  • 12
  • 21