How is a 'static inner class' different from a 'non-static inner class' in Java?

Understanding Static and Non-Static Inner Classes in Java

Java provides a unique feature called 'Inner Classes', which are classes defined within another class. There are two types of inner classes in Java, namely, 'static inner class' and 'non-static inner class' or 'inner class'. These two types have different behaviors especially in how they interact with the members of the outer class.

A 'Static Inner Class', as the term implies, is a static member of the outer class. Just like any other static members (methods, fields, and blocks), a static inner class can access static members of the outer class, including both methods and variables. This is due to the fact that static members belong to the class itself, as opposed to a specific instance of the class.

Here is an example of a static inner class:

public class OuterClass {
  static int staticVariable = 10;

  static class StaticInnerClass {
    void display() {
      System.out.println("Static variable: " + staticVariable);
    }
  }
}

In this example, StaticInnerClass can access the staticVariable of OuterClass because both are static members of OuterClass.

Conversely, a 'Non-Static Inner Class' or 'Inner Class' has access to all members of the outer class, even if they are defined as private. This is because an inner class is inherently associated with an instance of the outer class, and can thus access all the members, including both static and non-static, of the outer class.

Here is an example of a non-static inner class:

public class OuterClass {
  int nonStaticVariable = 20;

  class InnerClass {
    void display() {
      System.out.println("Non-static variable: " + nonStaticVariable);
    }
  }
}

In this example, InnerClass can access the nonStaticVariable of OuterClass because an inner class has access to all members of the outer class.

In summary, a Static Inner Class in Java is different from a Non-Static Inner Class mainly in terms of their access to members of the outer class. While a static inner class can only access the static members of the outer class, a non-static inner class can access all members of the outer class. Thus, when designing your classes, you should consider whether you need an inner class to have access to all members of the outer class or just the static members, and decide accordingly whether to use a static or non-static inner class.

Do you find this helpful?