Why do I need a static class?
Static variables are needed to access them, without creating an instance of the class. But why do we need a static class?
3 answers
A static class in java can only be a nested class. If a class is marked as static, it behaves like a normal class.
For example, there is a class A, a nested static class B, and a nested (non-static) class C:
public class A{
...
static public class B{
}
public class C{
}
}
And we want to create instances of these classes in the "external" code
public class Test{
public static void main(String[] args) {
A a = new A(); // обычный класс
A.B b = new A.B(); // статический вложенный класс
A.C c = a.new C(); // вложенный класс, связан с экземпляром А
// A.C c = new A.C(); // синтаксическая ошибка (не скомпилится)
}
}
Or inside static methods of class A
public class A{
...
static public class B{
}
public class C{
}
public static void main(String[] args) {
A a = new A(); // обычный класс
A.B b = new A.B(); // статический вложенный класс
A.C c = a.new C(); // вложенный класс, связан с экземпляром А
// A.C c = new A.C(); // синтаксическая ошибка (не скомпилится)
}
public static void test() {
A a = new A(); // обычный класс
A.B b = new A.B(); // статический вложенный класс
A.C c = a.new C(); // вложенный класс, связан с экземпляром А
// A.C c = new A.C(); // синтаксическая ошибка (не скомпилится)
}
}
In my opinion, the use of a static class may be appropriate, as a small class that by default the meaning is closely related to the" main " outer class.
For example:
public class Tree{
static public class Node{
}
}
In this situation, you can also move the nested class to a regular class and move both classes to a separate package.
The only difference between a nested static class and a regular one that I see is a more lenient attitude towards the visibility of methods and fields between the nested class and its outer class.
For example:
public class A {
private void privateMethod(){
B b = new B();
b.privateMethod(); // есть доступ к приватным методам/полям
}
static public class B {
private void privateMethod(){
A a = new A();
a.privateMethod(); // есть доступ к приватным методам/полям
}
}
}
Link to documentation:
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Basically, so that you can create nested classes, whose objects can be created without creating an instance of the class in which it lies.
"A static class in java can only be a nested class" - there are nested(static
) and internal, the difference is as in the usual plan, static
has access only to static fields