Java static class

Filed Under: Java

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


static class Test {

}

We get following compilation error.


$ javac Test.java 
Test.java:1: error: modifier static not allowed here
static class Test {
       ^
1 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.


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.


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.


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 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages