Java static class With Examples

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

We get following compilation error.

Java static class

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.

Java static class example

Let’s look at the example of java static class and see how we can use it in java program.

Now let’s see how to instantiate and use static nested class.

Java static class file

Java static class file is named as OuterClass$StaticClass.class. Below image shows this for our example program.

java-static-nested-class-example

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.

By admin

Leave a Reply

%d bloggers like this: