Why do I need static non-nested classes?
Why do I need static non-nested classes?
4 answers
To access static methods of static classes, you do not need to create an instance of them.
For example, the class Math
.
If the method Math.cos()
if it was not static, then before using the cosine function, you would have to write:
Math mathClass = new Math();
cosinusX = mathClass.cos(x);
And so we refer to the methods of the static class Math
simply by its name:
cosinusX = Math.cos(x)
You don't need them, so you can't create them.
UPD
By and large, all top - level classes behave like static ones - i.e. you don't need to create anything before instantiating them-so there's no need for this modifier and it's not just not supported by the specification.
Static classes cannot be created at the top level. If we are talking about Static Nested Classes, the answer is here or here. There are also usage examples. In short, static classes can be created without an instance of the class(enclosing class) in which it (the static class) is described. Example from docks:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
As already mentioned, you can't create static top-level classes.
As for the nested
classes, they have several differences compared to the inner
classes.
- Objects of these classes do not contain references to the object of the class in which it is located (
enclosing class
). Accordingly, less overhead in memory. - Creating an object of the
nested
class does not require an object of theenclosing
class, i.e. only one object is created:new Enclosing.Nested()