Inner classes in Java are classes defined within another class. They are used to logically group classes that are only used in one place, increase encapsulation, and can lead to more readable and maintainable code. There are several types of inner classes in Java, each with its own use case and characteristics.

Types of Inner Classes

  1. Member Inner Class
  2. Static Nested Class
  3. Local Inner Class
  4. Anonymous Inner Class

  1. Member Inner Class

A member inner class is defined within the body of an outer class and is treated like a member of the outer class. It can access all the members (including private members) of the outer class.

Example:

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

    class InnerClass {
        void display() {
            System.out.println("Accessing: " + outerField);
        }
    }

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

Explanation:

  • OuterClass contains a private field outerField.
  • InnerClass is a member inner class that has a method display which accesses outerField.
  • In the main method, an instance of InnerClass is created using an instance of OuterClass, and the display method is called.

  1. Static Nested Class

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

Example:

public class OuterClass {
    private static String staticOuterField = "Static outer field";

    static class StaticNestedClass {
        void display() {
            System.out.println("Accessing: " + staticOuterField);
        }
    }

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

Explanation:

  • StaticNestedClass is a static nested class that can access the static field staticOuterField of the outer class.
  • An instance of StaticNestedClass is created without needing an instance of OuterClass.

  1. Local Inner Class

A local inner class is defined within a block, typically a method. It can access the members of the enclosing block.

Example:

public class OuterClass {
    void outerMethod() {
        final String localVariable = "Local variable";

        class LocalInnerClass {
            void display() {
                System.out.println("Accessing: " + localVariable);
            }
        }

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

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

Explanation:

  • LocalInnerClass is defined within the outerMethod method.
  • It can access the local variable localVariable of the method.
  • An instance of LocalInnerClass is created and its display method is called within the outerMethod.

  1. Anonymous Inner Class

An anonymous inner class is a class without a name and is used to instantiate objects with certain "extras" such as method overrides. It is defined and instantiated in a single statement.

Example:

public class OuterClass {
    void outerMethod() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Running in an anonymous inner class");
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
    }

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

Explanation:

  • An anonymous inner class is created that implements the Runnable interface.
  • The run method is overridden to provide the implementation.
  • A Thread is created with the anonymous inner class and started.

Practical Exercises

Exercise 1: Member Inner Class

Create a member inner class that calculates the area of a rectangle.

Solution:

public class Rectangle {
    private int length;
    private int width;

    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    class AreaCalculator {
        int calculateArea() {
            return length * width;
        }
    }

    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle(5, 3);
        Rectangle.AreaCalculator calculator = rectangle.new AreaCalculator();
        System.out.println("Area: " + calculator.calculateArea());
    }
}

Exercise 2: Static Nested Class

Create a static nested class that calculates the factorial of a number.

Solution:

public class MathUtil {
    static class FactorialCalculator {
        int calculateFactorial(int n) {
            if (n == 0) return 1;
            return n * calculateFactorial(n - 1);
        }
    }

    public static void main(String[] args) {
        MathUtil.FactorialCalculator calculator = new MathUtil.FactorialCalculator();
        System.out.println("Factorial of 5: " + calculator.calculateFactorial(5));
    }
}

Summary

  • Member Inner Class: Defined within the body of an outer class, can access all members of the outer class.
  • Static Nested Class: A static member of the outer class, can access static members of the outer class.
  • Local Inner Class: Defined within a block, typically a method, can access members of the enclosing block.
  • Anonymous Inner Class: A class without a name, used for instantiating objects with method overrides.

Understanding inner classes can help you write more organized and maintainable code by logically grouping related classes and increasing encapsulation.

Java Programming Course

Module 1: Introduction to Java

Module 2: Control Flow

Module 3: Object-Oriented Programming

Module 4: Advanced Object-Oriented Programming

Module 5: Data Structures and Collections

Module 6: Exception Handling

Module 7: File I/O

Module 8: Multithreading and Concurrency

Module 9: Networking

Module 10: Advanced Topics

Module 11: Java Frameworks and Libraries

Module 12: Building Real-World Applications

© Copyright 2024. All rights reserved