Inner Classes and Encapsulation
What you'll learn: How inner classes can access private members of their outer class, making them powerful tools for tightly coupled helper logic.
The Relationship Between Inner Classes and Encapsulation
Inner classes have a special superpower: they can directly access all members of their outer class, including private fields and methods. This breaks the usual encapsulation rules in a controlled way, creating an intimate partnership between the outer and inner class.
Think of it like a trusted assistant with a master key. While the outside world can't peek into your private office, your assistant has full access because they work directly for you.
Why This Matters
This access privilege makes inner classes ideal for:
- Helper logic that needs to manipulate the outer class's internals
- Tight coupling where the inner class is meaningless without its outer context
- Encapsulation boundaries where only the outer class and its inner helper can see certain implementation details
Example Structure
public class BankAccount {
private double balance; // Private field
public class AuditLog {
public void logBalance() {
// Inner class directly accesses private balance!
System.out.println("Current balance: " + balance);
}
}
}
The AuditLog inner class can read balance directly, even though it's private. The outer class trusts its inner class completely. Together, they form a single encapsulation unit—outsiders can't access balance, but the inner helper can.
This design keeps sensitive logic contained within a single outer class boundary while organizing related functionality into logical inner components.
Key Takeaway: Inner classes can access private members of their outer class, making them perfect for tightly coupled helper logic that needs privileged access while maintaining overall encapsulation.