Chapter 46 of 77

Inner Classes in Java

So far, every class we have written has been a separate, top-level class. But Java also allows us to write a class inside another class.

class Outer {

    class Inner {
        // ...
    }
}

A class declared inside another class is called a nested class. Why would we want that? Sometimes a class is only useful to one other class. For example, a Node is only meaningful inside a linked list, and a Department only makes sense as part of a University. Putting the helper class inside keeps related code together and hides it from the rest of the program.

Java has four kinds of nested classes:

Nested classes
├── Static nested class        → declared with static, inside a class
└── Inner classes (non-static)
    ├── Member inner class     → declared inside a class, without static
    ├── Local class            → declared inside a method
    └── Anonymous class        → a class with no name, created on the spot

Let's look at each one.

Member Inner Class

A member inner class is a non-static class declared directly inside another class. Every inner object is tied to an object of the outer class.

Because it belongs to an outer object, an inner class can access all members of the outer class, even private ones.

class University {
    private String name = "IIT Delhi";

    class Department {
        String deptName;

        Department(String deptName) {
            this.deptName = deptName;
        }

        void show() {
            // An inner class can use the outer class's private fields
            System.out.println(deptName + " department of " + name);
        }
    }

    void createDepartment() {
        // Inside the outer class, we can create it directly
        Department d = new Department("Mechanical");
        d.show();
    }
}

class Main {
    public static void main(String[] args) {

        University university = new University();

        // Outside, we need an outer object first
        University.Department cse = university.new Department("CSE");
        cse.show();

        university.createDepartment();
    }
}

Output:

CSE department of IIT Delhi
Mechanical department of IIT Delhi

Notice the unusual syntax university.new Department("CSE"). Since a Department must belong to a particular University, we first need a University object and then create the inner object through it. The full type name of the inner class is University.Department.

If we try to create it without an outer object, like new University.Department() inside main(), the compiler says:

error: an enclosing instance that contains University.Department is required

Inside the outer class's own instance methods, such as createDepartment(), we can just write new Department(...), because this already refers to the outer object.

Outer.this: When Names Clash

What if the inner class has a field with the same name as the outer class? We already know this refers to the current object. Inside an inner class, this means the inner object. To reach the outer object, we write OuterClassName.this:

class Outer {
    int value = 10;

    class Inner {
        int value = 20;

        void show() {
            int value = 30;
            System.out.println(value);             // local variable
            System.out.println(this.value);        // Inner's field
            System.out.println(Outer.this.value);  // Outer's field
        }
    }
}

class Main {
    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.show();
    }
}

Output:

30
20
10

Java always picks the closest name first: the local variable, then the inner class's field, then the outer class's field.

Static Nested Class

A static nested class is declared with the static keyword. It belongs to the outer class itself, not to any outer object.

This follows the same rule we learned in the Static Keyword chapter: something static belongs to the class. So a static nested class does not need an outer object, and it can only directly use the outer class's static members.

class Order {
    private static int totalOrders = 0;
    private String customer;

    Order(String customer) {
        this.customer = customer;
        totalOrders++;
    }

    static class Item {
        String name;
        int price;

        Item(String name, int price) {
            this.name = name;
            this.price = price;
        }

        void show() {
            System.out.println(name + " : Rs. " + price);
            System.out.println("Orders so far: " + totalOrders); // static: OK
            // System.out.println(customer); // Error: customer belongs to an Order object
        }
    }
}

class Main {
    public static void main(String[] args) {

        new Order("Ravi");

        // No Order object is needed to create an Item
        Order.Item item = new Order.Item("Notebook", 60);
        item.show();
    }
}

Output:

Notebook : Rs. 60
Orders so far: 1

We create it with new Order.Item(...), with no Order object needed. If we uncomment the line that uses customer, we get:

error: non-static variable customer cannot be referenced from a static context

That is because customer belongs to a specific Order object, and an Item is not connected to any Order object.

A good rule of thumb: if the nested class does not need the outer object's fields, make it static. Static nested classes are simpler and lighter, because each inner-class object secretly keeps a reference to its outer object, while a static nested object does not.

Local Class

A local class is declared inside a method. Just like a local variable, it can only be used inside that method.

class Main {

    static void printReport(String studentName, int marks) {

        int passMarks = 40;   // effectively final: never changed

        class Report {
            void print() {
                String result = marks >= passMarks ? "PASS" : "FAIL";
                System.out.println(studentName + " scored " + marks + " : " + result);
            }
        }

        Report report = new Report();
        report.print();
    }

    public static void main(String[] args) {
        printReport("Neha", 78);
        printReport("Rahul", 35);
    }
}

Output:

Neha scored 78 : PASS
Rahul scored 35 : FAIL

A local class can use the method's parameters and local variables, but only if they are final or effectively final. "Effectively final" means the variable is never changed after it is first assigned, even though it is not marked final. Here, studentName, marks, and passMarks are never changed, so the code works.

If we changed one of them, for example by writing passMarks++ somewhere in the method, the compiler would report:

error: local variables referenced from an inner class must be final or effectively final

Local classes are not very common in everyday code, but they help you understand the next type, which is used a lot.

Anonymous Class

An anonymous class is a class without a name, declared and instantiated in a single expression. It either implements an interface or extends a class.

Anonymous classes are useful when we need a one-time implementation of an interface or a one-time change to a class's behaviour, and creating a whole new named class would be overkill.

interface Greeting {
    void greet(String name);
}

class Notifier {
    void send(String message) {
        System.out.println("Email: " + message);
    }
}

class Main {
    public static void main(String[] args) {

        // 1. Anonymous class implementing an interface
        Greeting hindi = new Greeting() {
            @Override
            public void greet(String name) {
                System.out.println("Namaste, " + name + "!");
            }
        };

        Greeting english = new Greeting() {
            @Override
            public void greet(String name) {
                System.out.println("Hello, " + name + "!");
            }
        };

        hindi.greet("Arjun");
        english.greet("Arjun");

        // 2. Anonymous class extending a class and overriding a method
        Notifier sms = new Notifier() {
            @Override
            void send(String message) {
                System.out.println("SMS: " + message);
            }
        };

        Notifier email = new Notifier();

        email.send("Your order is confirmed");
        sms.send("Your order is confirmed");
    }
}

Output:

Namaste, Arjun!
Hello, Arjun!
Email: Your order is confirmed
SMS: Your order is confirmed

Let's break down the syntax:

Greeting hindi = new Greeting() {     ← "create an object of a new class that implements Greeting"
    @Override
    public void greet(String name) {  ← the class body: implement the method
        ...
    }
};                                    ← the semicolon ends the whole statement

We cannot normally write new Greeting(), because Greeting is an interface. Adding a class body { ... } after it creates a nameless class that implements Greeting, and immediately creates one object of it. The same works with abstract classes and normal classes, as the Notifier example shows.

A few rules to remember:

  • An anonymous class has no name, so it cannot have a constructor.

  • It can implement one interface or extend one class, not both.

  • Like local classes, it can only use local variables that are final or effectively final.

Later, in the Lambda Expressions chapter, you will see a much shorter way to write an anonymous class when the interface has just one abstract method. Anonymous classes are still needed when there is more than one method to implement or when you are extending a class.

How Nested Classes Are Compiled

Even though a nested class is written inside another class in the source code, the compiler turns every nested class into its own separate .class file with a $ in its name. Compiling the examples above produces files like these:

University$Department.class   ← member inner class
Order$Item.class              ← static nested class
Main$1Report.class            ← local class (numbered)
Main$1.class, Main$2.class    ← anonymous classes (just numbers, no name)

If you see files with $ in your output folder, now you know where they come from.

A Complete Example

Here is a small list of numbers built from linked nodes. It uses a private static nested class for the nodes (a node doesn't need the list object) and a member inner class for printing (the printer needs the list's head). You will see this exact Node pattern again when we study linked lists.

class NumberList {

    // A private static nested class: only NumberList uses it
    private static class Node {
        int value;
        Node next;

        Node(int value) {
            this.value = value;
        }
    }

    private Node head;
    private int size;

    void add(int value) {
        Node newNode = new Node(value);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
        size++;
    }

    // A non-static inner class: it needs the list's head
    class Printer {
        void print() {
            Node current = head;
            System.out.print("List (" + size + " items):");
            while (current != null) {
                System.out.print(" " + current.value);
                current = current.next;
            }
            System.out.println();
        }
    }
}

class Main {
    public static void main(String[] args) {

        NumberList list = new NumberList();
        list.add(5);
        list.add(10);
        list.add(15);

        NumberList.Printer printer = list.new Printer();
        printer.print();

        list.add(20);
        printer.print();   // the inner object sees the updated list
    }
}

Output:

List (3 items): 5 10 15
List (4 items): 5 10 15 20

Because Node is private, code outside NumberList cannot even see it. That is the main advantage of nested classes: they let a class keep its helper classes as hidden implementation details. The Printer object also sees the updated list after we add 20, because it reads the fields of the same NumberList object it was created from.

Comparing the Four Types

Type

Declared

Needs outer object?

Can access

Typical use

Static nested

Inside a class, with static

No

Outer's static members

Helper classes like Node, grouping related classes

Member inner

Inside a class, without static

Yes

All outer members, including private

Objects that work closely with one outer object

Local

Inside a method

Only if declared in an instance method

Outer members + effectively final locals

Helper used by just one method

Anonymous

Inside an expression

Only if created in an instance method

Outer members + effectively final locals

One-time implementation of an interface or class

Common Mistakes

  • Creating an inner object without an outer object. Use outer.new Inner(), or make the nested class static if it doesn't need the outer object.

  • Using a non-static inner class when static would do. Each inner object holds a hidden reference to its outer object. If the inner object lives long, it keeps the outer object in memory too.

  • Modifying a captured local variable. Local and anonymous classes can only read local variables that are effectively final.

  • Forgetting the semicolon after an anonymous class. The class body is part of an assignment statement, so it ends with };.

  • Confusing this. Inside an inner or anonymous class, this refers to the inner object. Use Outer.this for the outer one.

The Main Idea

Nested classes let you place a class where it logically belongs. Use a static nested class for helpers that don't need an outer object, a member inner class when each object must work with a specific outer object, and an anonymous class for quick, one-time implementations.

Static nested → belongs to the outer class. Inner → belongs to an outer object.