In Java, a class can be defined within another class. These types of classes are called nested classes or inner classes. The class in which the nested class is defined is known as the outer class.
Although an inner class can either be static or non-static, the static
keyword in java can only be used for an inner class and not with an outer class. Hence, the concept of static classes simply provides a way of grouping classes together in Java.
Static classes are defined the same way as other inner classes in Java, the only difference being the static
keyword behind the class name.
The syntax for creating a static class is as follows:
class Employee {
//private fields
public static class Validator {
//methods
}
}
The concept of static classes was introduced under the concept of inner classes, which are specially designed to handle some delicate functionality in a class.
A static class can access members, i.e., variables or methods of its outer-containing class.
Some attributes that differentiate a static class from a non-static inner class include:
A static inner class may be instantiated without instantiating its outer class, i.e., a static class does not need to create an instance of its outer containing class in order to create its own instance.
A static class can only access members of its outer containing class if the members are static in nature. This means that a static nested class does not have access to the instance variables and methods of the outer class that are non-static.
An example of a static class implementation is as follows:
class Employee {private static String name = "Smith";public static class Validator {public void testMethod() {System.out.println("This is a message from nested static class to " + name);}}public static void main(String args[]) {Employee.Validator nested = new Validator();nested.testMethod();}}
The output of the above program is:
This is a message from nested static class to Smith
Here, the inner class was able to access the field of the outer class because it is also a static member. If the field is made a non-static variable, there will be a compiler error.
The static inner class (Validator
) was also instantiated without having to instantiate its outer class (Employee
), and its method was called successfully.
The use of the static class is primarily for memory management. This is possible because static classes are only loaded by the class loader at the time of the first usage and not when its enclosing class gets loaded in JVM. Finally, it also helps when grouping classes together.