Nested and Inner Classes


1. Nested Classes in Java

A nested class is any class defined inside another class. Java allows classes to be nested for better organization, encapsulation, and readability.

There are two main types:

A. Static Nested Class

  • Declared static inside another class.
  • Can access only static members of the outer class directly.
  • Does not have a reference to the outer class instance.
  • Can be instantiated without an instance of the outer class.

Example:

class Outer {
    static int outerStatic = 10;

    static class Nested {
        void display() {
            System.out.println("Static Nested class: " + outerStatic);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Outer.Nested nested = new Outer.Nested();
        nested.display();
    }
}

Output:

Static Nested class: 10

B. Inner Classes (Non-Static Nested Class)

  • Declared without static inside another class.
  • Can access all members (including private) of the outer class.
  • Has an implicit reference to the outer class instance.
  • Cannot have static members (except final constants).
  • Needs an instance of the outer class to be created.

Example:

class Outer {
    private int outerVar = 5;

    class Inner {
        void display() {
            System.out.println("Inner class: " + outerVar);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner(); // note: outer.new Inner()
        inner.display();
    }
}

Output:

Inner class: 5

2. Other Types of Inner Classes

Java also supports special forms of inner classes:

  1. Local Inner Class
    • Defined inside a method.Can access final or effectively final variables of the method.
class Outer {
    void show() {
        int num = 10;
        class LocalInner {
            void display() {
                System.out.println("Local inner class: " + num);
            }
        }
        LocalInner li = new LocalInner();
        li.display();
    }
}
  1. Anonymous Inner Class
    • Defined without a class name.Typically used for interfaces or abstract classes on-the-fly.
abstract class Person {
    abstract void greet();
}

public class Test {
    public static void main(String[] args) {
        Person p = new Person() {
            void greet() {
                System.out.println("Hello from anonymous class!");
            }
        };
        p.greet();
    }
}

3. Key Differences Between Static Nested and Inner Classes

FeatureStatic Nested ClassInner Class (Non-static)
Reference to outer classNoYes
Can access outer class membersOnly static membersAll members
InstantiationOuter.Nested nested = new Outer.Nested();Outer.Inner inner = outer.new Inner();
Can have static membersYesNo

Leave a Reply