Static variables are needed to access them without creating an instance of the class. But why do we need a static class?
Answer 1, authority 100%
Only a nested class can be a static class in java.
If a class is marked static then it behaves like a regular class.
for example, there is class A, nested static class B and 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 “external” code
public class Test {
public static void main (String [] args) {
A a = new A (); // normal class
A.B b = new A.B (); // static nested class
A.C c = a.new C (); // nested class associated with instance A
// A.C c = new A.C (); // syntax error (won't compile)
}
}
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 (); // normal class
A.B b = new A.B (); // static nested class
A.C c = a.new C (); // nested class associated with instance A
// A.C c = new A.C (); // syntax error (won't compile)
}
public static void test () {
A a = new A (); // normal class
A.B b = new A.B (); // static nested class
A.C c = a.new C (); // nested class associated with instance A
// A.C c = new A.C (); // syntax error (won't compile)
}
}
In my opinion, the use of a static class may be appropriate as a small class, which in its 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 into a regular one and move both classes into a separate package.
The only difference between a nested static class and a regular class that I see is a more forgiving attitude to visibility
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 (); // there is access to private methods / fields
}
static public class B {
private void privateMethod () {
A a = new A ();
a.privateMethod (); // there is access to private methods / fields
}
}
}
Link to documentation:
https://docs.oracle.com/javase/tutorial/java/javaOO /nested.html
Answer 2, authority 48%
Basically so that you can create nested classes, objects of which can be created without creating an instance of the class in which it lies.
Answer 3
“Only a nested class can be a static class in java” – there are nested (static
) and internal ones, the difference, as in the usual plan, static
has access only to static fields