Today we will look into java static class. It’s a good interview question to test your knowledge about nested classes in java.
Java doesn’t allow top level static classes, for example if we try to make a class static like below.
Test.java
1 2 3 4 |
static class Test { } |
We get following compilation error.
1 2 3 4 5 6 7 |
$ javac Test.java Test.java:1: error: modifier static not allowed here static class Test { ^ 1 error |
Java static class
So is it possible to have static class in java?
Yes, java supports nested classes and they can be static. These static classes are also called static nested classes.
Java static nested class can access only static members of the outer class. Static nested class behaves similar to top-level class and is nested for only packaging convenience.
An instance of static nested class can be created like below.
1 2 3 4 |
OuterClass.StaticNestedClass nestedObj = new OuterClass.StaticNestedClass(); |
Java static class example
Let’s look at the example of java static class and see how we can use it in java program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.journaldev.java.examples; public class OuterClass { private static String name = "OuterClass"; // static nested class static class StaticNestedClass { private int a; public int getA() { return this.a; } public String getName() { return name; } } } |
Now let’s see how to instantiate and use static nested class.
1 2 3 4 5 6 7 8 9 10 11 |
package com.journaldev.java.examples; public class StaticNestedClassTest { public static void main(String[] args) { //creating instance of static nested class OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass(); //accessing outer class static member System.out.println(nested.getName()); } } |
Java static class file
Java static class file is named as OuterClass$StaticClass.class
. Below image shows this for our example program.
Java static class benefits
The only benefit I could think of is encapsulation. If the static nested class works only with the outer class then we can keep nested class as static to keep them close.