Accessing Outer Class Fields from Inner Classes
What you'll learn: How inner classes can directly reach into their outer class to access any field—even private ones.
The Special Relationship
One of the most powerful features of inner classes is their privileged access to the outer class. Unlike separate top-level classes, an inner class has an invisible connection to its enclosing instance. This means the inner class can see and use all fields of the outer class, regardless of access modifiers—including private fields that would normally be hidden from everyone else.
Think of it like being a family member with a key to every room in the house. While strangers (other classes) need to use the front door (public methods), you (the inner class) can walk directly into any room (field), even private ones.
How It Works
When you access an outer class field from inside an inner class, Java automatically knows you mean the field from the enclosing instance. You simply reference the field by name:
public class BankAccount {
private double balance; // Private field
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public class Transaction {
public void withdraw(double amount) {
// Inner class directly accesses private field!
balance = balance - amount;
}
public void displayBalance() {
// Again, direct access
System.out.println("Balance: " + balance);
}
}
}
The Transaction inner class reaches right into balance, even though it's private. This happens because each Transaction instance is tied to a specific BankAccount instance.
Key Takeaway: Inner classes have complete access to all fields and methods of their enclosing outer class, including private members, making them ideal for implementing tightly-coupled helper functionality.