0Pricing
Java Academy · Lesson

Inner Classes and Outer Access

Use non-static inner classes that hold a reference to the outer class instance.

Inner Classes

A non-static inner class holds an implicit reference to the enclosing outer class instance. It can access all members of the outer class, including private ones.

Declaring and Using an Inner Class

Create an inner class instance only through an outer class instance using outer.new InnerClass().

class BankAccount {
    private double balance;
    private String owner;

    BankAccount(String owner, double initial) {
        this.owner = owner; this.balance = initial;
    }

    class Transaction {
        void deposit(double amount) {
            balance += amount; // accesses outer field directly
            System.out.println(owner + " deposited " + amount);
        }
    }
}

BankAccount acct = new BankAccount("Alice", 500);
BankAccount.Transaction tx = acct.new Transaction();
tx.deposit(100); // Alice deposited 100.0

All lessons in this course

  1. Static Nested Classes
  2. Inner Classes and Outer Access
  3. Local and Anonymous Classes
  4. Choosing the Right Nesting Strategy
← Back to Java Academy