Why do I need static non-nested classes?

Why do I need static non-nested classes?

Author: Nicolas Chabanovsky, 2011-08-25

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)
 5
Author: megacoder, 2017-11-18 22:59:45

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.

 2
Author: yozh, 2011-08-25 12:33:31

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();
 1
Author: A.A.Rudenko, 2016-08-16 09:16:05

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.

  1. 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.
  2. Creating an object of the nested class does not require an object of the enclosing class, i.e. only one object is created: new Enclosing.Nested()
 1
Author: Artem Konovalov, 2016-08-16 10:31:57