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.0All lessons in this course
- Static Nested Classes
- Inner Classes and Outer Access
- Local and Anonymous Classes
- Choosing the Right Nesting Strategy