java
  1. java-inner-classes

Java Inner Classes

In Java, an inner class is a class that is defined inside another class. This guide will explore the syntax, types, usage, and considerations for using inner classes in Java.

Syntax

The syntax for defining an inner class is as follows:

public class OuterClass {
    // Outer class members and methods

    public class InnerClass {
        // Inner class members and methods
    }
}

Example

Let's consider an example that demonstrates the usage of inner classes:

public class OuterClass {
    private int outerData = 10;

    public class InnerClass {
        private int innerData = 20;

        public void displayData() {
            System.out.println("Outer Data: " + outerData);
            System.out.println("Inner Data: " + innerData);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the outer class
        OuterClass outerObj = new OuterClass();

        // Creating an instance of the inner class
        OuterClass.InnerClass innerObj = outerObj.new InnerClass();

        // Accessing the inner class method
        innerObj.displayData();
    }
}

Output

The output will display the data from both the outer and inner classes:

Outer Data: 10
Inner Data: 20

Explanation

  • An inner class can access the members (fields and methods) of its outer class, including private members.
  • The new keyword is used to create an instance of the inner class.

Use

Inner classes are useful:

  • When a class is only relevant to its outer class and does not make sense on its own.
  • For implementation of complex data structures or algorithms where a helper class is needed.
  • In event handling to define event listeners within a class.

Important Points

  • There are four types of inner classes: Member Inner Class, Local Inner Class, Anonymous Inner Class, and Static Nested Class.
  • Inner classes can be private, protected, default, or public.
  • Inner classes have access to the members of the outer class, even if they are private.

Summary

Java inner classes provide a way to logically group classes within other classes. They enhance code modularity, encapsulation, and readability. Understanding the types of inner classes and their appropriate use cases contributes to writing more maintainable and organized Java code. Inner classes are a powerful feature of the Java programming language that allows developers to structure their code in a more intuitive and organized manner.

Published on: