TExcelTAD
Home › Java › Java Inner Classes

Java Inner Classes

Java lets you declare a class inside another class. Such nested classes keep helper types close to the only place they're used, and they can access the enclosing class's members — even private ones. There are four kinds:

Kind Declared Has access to outer instance?
Inner class (non-static member) inside a class body yes
Static nested class inside a class body, with static no
Local class inside a method yes (if the method isn't static), plus effectively final locals
Anonymous class inline in an expression, no name same as local

Inner classes

An inner class instance is always tied to an instance of the outer class, so it can use the outer object's fields directly. You create one from an outer object with outer.new Inner():

java · try it yourself
class Building {
    private final String name;
    private int visitors = 0;

    Building(String name) {
        this.name = name;
    }

    class Door {
        private final String side;

        Door(String side) {
            this.side = side;
        }

        void enter() {
            visitors++;   // the outer object's private field
            System.out.println("Entered " + name + " through the " + side + " door");
        }
    }

    int getVisitors() {
        return visitors;
    }
}

class Main {
    public static void main(String[] args) {
        Building museum = new Building("City Museum");
        Building.Door front = museum.new Door("front");
        Building.Door back = museum.new Door("back");
        front.enter();
        back.enter();
        front.enter();
        System.out.println("Visitors: " + museum.getVisitors());
    }
}
Entered City Museum through the front door
Entered City Museum through the back door
Entered City Museum through the front door
Visitors: 3

Static nested classes

A static nested class is not tied to an outer instance — it's essentially a normal class that lives in the outer class's namespace. It's the most common kind, often used for builders, results or small data types:

java · try it yourself
class Geometry {
    static class Point {
        final double x, y;

        Point(double x, double y) {
            this.x = x;
            this.y = y;
        }

        double distanceTo(Point other) {
            return Math.hypot(other.x - x, other.y - y);
        }
    }

    static double perimeter(Point... pts) {
        double sum = 0;
        for (int i = 0; i < pts.length; i++) {
            sum += pts[i].distanceTo(pts[(i + 1) % pts.length]);
        }
        return sum;
    }
}

class Main {
    public static void main(String[] args) {
        Geometry.Point a = new Geometry.Point(0, 0);
        Geometry.Point b = new Geometry.Point(3, 0);
        Geometry.Point c = new Geometry.Point(3, 4);
        System.out.println("a to c: " + a.distanceTo(c));
        System.out.println("Triangle perimeter: " + Geometry.perimeter(a, b, c));
    }
}
a to c: 5.0
Triangle perimeter: 12.0

Tip: If a nested class doesn't need the outer instance, make it static. It's cheaper (no hidden reference to the outer object) and easier to create.

Local classes

A class declared inside a method is visible only in that method. It can read the method's local variables as long as they are effectively final (never reassigned):

java · try it yourself
class Main {
    static void printReport(String title, int[] values) {
        int width = 20;   // effectively final

        class Line {
            void print(String label, int value) {
                String dots = ".".repeat(width - label.length() - String.valueOf(value).length());
                System.out.println(label + dots + value);
            }
        }

        Line line = new Line();
        System.out.println(title);
        line.print("Minimum", java.util.Arrays.stream(values).min().getAsInt());
        line.print("Maximum", java.util.Arrays.stream(values).max().getAsInt());
        line.print("Count", values.length);
    }

    public static void main(String[] args) {
        printReport("Daily steps", new int[] {4200, 12850, 8030, 950});
    }
}
Daily steps
Minimum..........950
Maximum........12850
Count..............4

Anonymous classes

An anonymous class declares and instantiates a one-off implementation of an interface or subclass in a single expression. Before lambdas (Java 8) this was the usual way to pass behaviour around:

java · try it yourself
import java.util.Arrays;
import java.util.Comparator;

interface Greeter {
    String greet(String name);
}

class Main {
    public static void main(String[] args) {
        Greeter formal = new Greeter() {
            @Override
            public String greet(String name) {
                return "Good evening, " + name + ".";
            }
        };
        System.out.println(formal.greet("Dr. Lee"));

        String[] words = {"banana", "kiwi", "cherry", "fig"};
        Arrays.sort(words, new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return Integer.compare(a.length(), b.length());
            }
        });
        System.out.println(Arrays.toString(words));
    }
}
Good evening, Dr. Lee.
[fig, kiwi, banana, cherry]

For interfaces with a single abstract method, a lambda does the same with far less code: (a, b) -> Integer.compare(a.length(), b.length()). You'll meet lambdas in the Advanced section.

Test yourself

How do you create an instance of a non-static inner class Inner of Outer?

  1. new Outer.Inner()
  2. outerObj.new Inner()
  3. Inner.new()
  4. Outer.Inner.create()

Which nested class does NOT hold a reference to an outer instance?

  1. Inner class
  2. Static nested class
  3. Anonymous class in an instance method
  4. Local class in an instance method

Which local variables can a local or anonymous class use?

  1. Any local variable
  2. Only static variables
  3. Only final or effectively final ones
  4. None