Java Nested Classes

Introduction

Nested classes are classes defined within another class. Java supports several types of nested classes, each serving different purposes and offering various levels of access and functionality. The types of nested classes include Static Nested Classes, Inner Classes, Local Inner Classes, and Anonymous Inner Classes.

Table of Contents

  1. What are Nested Classes?
  2. Types of Nested Classes
  3. Static Nested Class
  4. Inner Class
  5. Local Inner Class
  6. Anonymous Inner Class
  7. Real-World Analogy
  8. Examples
  9. Conclusion

1. What are Nested Classes?

Nested classes are classes defined within the scope of another class. They can be categorized as static nested classes and non-static nested classes (inner classes). Nested classes can be useful for logically grouping classes that are only used in one place, increasing encapsulation and improving code readability.

2. Types of Nested Classes

Java supports four types of nested classes:

  1. Static Nested Class
  2. Inner Class (Non-static Nested Class)
  3. Local Inner Class (Defined inside a block)
  4. Anonymous Inner Class

3. Static Nested Class

A static nested class is a static class defined within another class. It can access the static members of the outer class but cannot directly access the non-static members.

Example: Static Nested Class

public class OuterClass {
    private static String staticOuterField = "Static Outer Field";
    private String nonStaticOuterField = "Non-Static Outer Field";

    static class StaticNestedClass {
        void display() {
            // Can access static members of the outer class
            System.out.println("Static Nested Class accessing: " + staticOuterField);
            // Cannot access non-static members of the outer class directly
            // System.out.println("Non-Static Outer Field: " + nonStaticOuterField); // Error
        }
    }

    public static void main(String[] args) {
        OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
        nestedObject.display();
    }
}

Output:

Static Nested Class accessing: Static Outer Field

4. Inner Class

An inner class is a non-static nested class. It can access both static and non-static members of the outer class. It is associated with an instance of the outer class.

Example: Inner Class

public class OuterClass {
    private String outerField = "Outer Field";

    class InnerClass {
        void display() {
            // Can access both static and non-static members of the outer class
            System.out.println("Inner Class accessing: " + outerField);
        }
    }

    public static void main(String[] args) {
        OuterClass outerObject = new OuterClass();
        OuterClass.InnerClass innerObject = outerObject.new InnerClass();
        innerObject.display();
    }
}

Output:

Inner Class accessing: Outer Field

5. Local Inner Class

A local inner class is a class defined within a method or any block of code. It has access to the local variables of the block where it is defined, provided the local variables are final or effectively final.

Example: Local Inner Class

public class OuterClass {
    void display() {
        final String localVariable = "Local Variable";

        class LocalInnerClass {
            void show() {
                System.out.println("Local Inner Class accessing: " + localVariable);
            }
        }

        LocalInnerClass localInner = new LocalInnerClass();
        localInner.show();
    }

    public static void main(String[] args) {
        OuterClass outerObject = new OuterClass();
        outerObject.display();
    }
}

Output:

Local Inner Class accessing: Local Variable

6. Anonymous Inner Class

An anonymous inner class is a class without a name and is defined and instantiated in a single statement. It is used for implementing interfaces or extending classes on the fly.

Example: Anonymous Inner Class

interface Greeting {
    void greet();
}

public class OuterClass {
    void display() {
        Greeting greeting = new Greeting() {
            @Override
            public void greet() {
                System.out.println("Hello from Anonymous Inner Class");
            }
        };
        greeting.greet();
    }

    public static void main(String[] args) {
        OuterClass outerObject = new OuterClass();
        outerObject.display();
    }
}

Output:

Hello from Anonymous Inner Class

7. Real-World Analogy

Consider a company:

  • The company (Outer Class) has different departments (Nested Classes).
  • Each department can have its own specific functionalities (methods) and properties (fields).
  • Some departments (Static Nested Class) are static, like HR policies.
  • Some departments (Inner Class) are closely tied to the company operations, like a software development team.
  • Temporary teams (Local Inner Class) formed for short-term projects.
  • Special task forces (Anonymous Inner Class) for specific tasks.

8. Examples

Example: Comprehensive Example

public class OuterClass {
    private static String staticOuterField = "Static Outer Field";
    private String outerField = "Outer Field";

    // Static Nested Class
    static class StaticNestedClass {
        void display() {
            System.out.println("Static Nested Class accessing: " + staticOuterField);
        }
    }

    // Inner Class
    class InnerClass {
        void display() {
            System.out.println("Inner Class accessing: " + outerField);
        }
    }

    void display() {
        final String localVariable = "Local Variable";

        // Local Inner Class
        class LocalInnerClass {
            void show() {
                System.out.println("Local Inner Class accessing: " + localVariable);
            }
        }

        LocalInnerClass localInner = new LocalInnerClass();
        localInner.show();
    }

    void anonymousClassExample() {
        Greeting greeting = new Greeting() {
            @Override
            public void greet() {
                System.out.println("Hello from Anonymous Inner Class");
            }
        };
        greeting.greet();
    }

    public static void main(String[] args) {
        // Static Nested Class
        OuterClass.StaticNestedClass staticNested = new OuterClass.StaticNestedClass();
        staticNested.display();

        // Inner Class
        OuterClass outerObject = new OuterClass();
        OuterClass.InnerClass innerObject = outerObject.new InnerClass();
        innerObject.display();

        // Local Inner Class
        outerObject.display();

        // Anonymous Inner Class
        outerObject.anonymousClassExample();
    }
}

Output:

Static Nested Class accessing: Static Outer Field
Inner Class accessing: Outer Field
Local Inner Class accessing: Local Variable
Hello from Anonymous Inner Class

9. Conclusion

Nested classes in Java provide a way to logically group classes that are only used in one place, increasing encapsulation and improving code readability. They can be static (static nested class) or non-static (inner class). Local inner classes are defined within a method or block, and anonymous inner classes are used for quick, one-time implementations. Understanding and utilizing nested classes can help create more organized and maintainable Java code.

Leave a Comment

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

Scroll to Top