Why can we create more than one instance of a static class? I try to find parallel between static class and static method, but this fact confuses me.
-
The commonality of static methods and static classes is that both do not belong to an instance of the class they are in. – zapl May 05 '16 at 11:39
-
I think, this post would answer all of your queries: http://stackoverflow.com/questions/15448352/why-is-class-declared-as-static-in-java – VivekJ May 05 '16 at 11:39
3 Answers
A static class is a nested class (i.e. it is declared within another class). It behaves like a top level class, which means you can create multiple instances of it.
It doesn't have much in common with static methods or static variables.

- 387,369
- 54
- 702
- 768
-
1I agree with your first two sentences. But static nested classes do have something in common with static methods or static variables, namely that you can access them without an instance of the outer class. – Sebastian Aug 04 '21 at 19:59
First of all - you can not create top-level static class. Static classes refer to nested classes.
You create static nested class when it's somehow related with class that contains it and initialization of nested class without its parent would not have sense.

- 550
- 3
- 12
-
While one indeed cannot use the keyword static for classes at top-level, this is not because they can't be static, but just because at top-level static is the default. The top-level class is accessible without an instance, so it is static. A static nested class behaves the same as a top-level class, just that you have to access it via the name-space of the outer class, so I agree with the second part of your post. A non-static nested class (inner class) finally depends on an instance of the outer class. – Sebastian Aug 04 '21 at 19:55
To understand why inner classes are defined as being static, imagine what it would mean if they were not static: instead of being generally available, the inner class definition would belong to an instance of the outer class. That makes no real sense since class definitions such as these already exist at compile time. As a result, there is no case to be made for them not being static.

- 409
- 3
- 7
-
nested classes can be both, static and non-static. In the latter case they are true inner classes and indeed do depend on an instance of the outer class! An instance of such an inner class can be created from an instance "outer" of the Outer class with `outer.new Inner()` – Sebastian Aug 04 '21 at 19:50