Static Nested and Inner Classes in Java

We can create a class within a class.

  • nested classes that are declared static are called static nested classes
  • nested classes that are non-static are called inner classes

static nested classes

  • static nested classes do not have access to any instance members of the enclosing outer class; it can only access them through an object’s reference
  • static nested classes can access all static members of the enclosing class, including private ones
  • Java programming specification doesn’t allow us to declare the top-level class as static; only classes within the classes (nested classes) can be made as static
  • We don’t need to create an instance of Outer class for creating an instance of the static class.

Non-static nested classes a.k.a Inner Classes

  • Non-static nested classes in Java are also called inner classes. Inner classes are associated with an instance of the enclosing class. Thus, you must first create an instance of the enclosing class to create an instance of an inner class.
  • Non-static nested classes (inner classes) have access to the fields of the enclosing class, even if they are declared private.
  • If a Java inner class declares fields or methods with the same names as field or methods in its enclosing class, the inner fields or methods are said to shadow over the outer fields or methods.
package com.java.core;

public class TestStatic {

    static class NestedStaticClass {

        public void method() {
            System.out.println("method invoked");
        }

    }

    class InnerClass {

        public void innermethod() {
            System.out.println("innermethod invoked");
        }

    }

    public static void main(String[] args) {

        // You can directly instantiate nested static class
        NestedStaticClass nestedStaticClass = new NestedStaticClass();
        nestedStaticClass.method();

        TestStatic testStatic = new TestStatic();
        // instantiation of inner class
        TestStatic.InnerClass innerClass = testStatic.new InnerClass();
        innerClass.innermethod();
    }

}
method invoked
innermethod invoked

Also, have a look into Anonymous Class

Leave a Reply

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