In previous article, we have provided details about What are static members in Java? now in this article, we will see what is static class in Java, how to declare static class and use it, with an example.

Some classes in Java can be made static, but it should be nested inside another class, basically we cannot declare outer class as static, Static classes are always nested inside non-static class.

So, we cannot use static keyword on class unless it is nested inner class. It can be accessed without instantiating the outer class, using other static members.

Note: In java, we can’t make the Top-level (outer) class static. Only nested classes can be static.

These nested static classes can access only the static members of the enclosing class since it does not have any reference to instances of the enclosing class.


class OuterClass{
   static class NestedStaticClass {
       //static class methods

Basic example:

public class Test { 
  class A { 
  static class B {
  public static void main(String[] args) { 

    /*will fail - compilation error, you need an instance of Class Test to instantiate Class A*/
    A a = new A(); 

    /*will compile successfully, not instance of class Test is needed to instantiate Class B */
    B b = new B(); 

As you can see in the above code, we can directly create class B object as it is declared static, but we cannot create Class A object without creating Test class object.

Let's take a look at a more detailed example.

package javaStatic;

public class OuterClass {

    String outerField = "Outer field variable";
    static String staticOuterField = "Static outer field variable";

    class InnerClass {
        void accessMembers() {

    static class StaticNestedClass {
        void accessMembers(OuterClass outer) {
            // Compiler error: Cannot make a static reference to the non-static
            //     field outerField
            // System.out.println(outerField);

    public static void main(String[] args) {
        System.out.println("Inner class:");
        OuterClass outerObject = new OuterClass();
        OuterClass.InnerClass innerObject = InnerClass(); //non-static class object creation call

        System.out.println("\nStatic nested class:");
        StaticNestedClass staticNestedObject = new StaticNestedClass();   //static class object creation class   


Inner class:
Outer field
Static outer field

Static nested class:
Outer field
Static outer field

As you can see above, that a static nested class interacts with the instance members of its outer class just like any other top-level class.

The static nested class StaticNestedClass can't directly access outerField because it's an instance variable of the enclosing class, OuterClass.

You may also like to read:

Various Java programming examples with output

Hello World program in Java (Your first Java program)

Best Java IDE for making easy to code in Java. (Eclipse, Netbeans or Any other?)