In this section, we will learn what the static class is and how to use it in Java.
Note: you should be already familiar with nested classes.
What Is Static Class in Java?
A class that is declared inside another class can be declared as static as well.
By default, an inner class can access all the members of the outer class no-matter if those are private or public. But if we want the inner class to have this accessibility, we can turn the inner class into static and in that case it will only access to those static members of the outer class (if any).
How to create a static class in Java?
To create a static class, simply put the keyword `static` in front of the `class` keyword.
Example:
static class ClassName{…}
Notes to consider when using a static class:
- ONLY INNER CLASSES CAN BE DECLARED AS STATIC.
- A static class can only access the static members of the enclosing class.
How to access a static class?
To access the static inner class, we use the name of the outer class before calling the inner class.
Example:
OuterClass.InnerStaticClass;
Example: creating and using static class in Java
Create a file named `Outer` and put the code below into that file:
public class Outer { private static String name = "Outer"; public static class Inner{ public static void printName(){ System.out.println(name); } } }
Now create another file named `Simple` and put the code below in there:
public class Simple { public static void main(String[] args) { Outer.Inner.printName(); } }
Output: Outer
In this example, the class named `Outer` has one static inner class named `Inner` and one static variable named `name`.
Accessing Static member of the Enclosing Class from within the Static Inner Class
The inner class has the access to either public or private static members of the outer class and as you can see inside the body of the `printName()` method that belongs to the inner class, we could access the private static member of the Outer class.
Now within the body of the `main()` method, we called this `printName()` method and sent the value of the `name` variable` to the output stream.