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?
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?
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.
Top-level classes can't be declared static
, only nested classes can be:
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
The difference is that:
The above is taken from the Java OO tutorial. You can read more here.
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.