Inner Classes
TL;DR
- An Inner Class is a non-static nested class.
- It is inextricably linked to an instance of the outer class.
- It has full, unrestricted access to all variables and methods of the outer class, even
privateones.
Concept
Think of an Outer Class as a Human, and an Inner Class as a Heart. A Heart makes no sense without a Human body to reside in.
Because the Heart is part of the Human, it can access the Human’s private blood stream.
You cannot instantiate an Inner Class without first instantiating the Outer Class. The JVM secretly passes a reference of the Outer object into the Inner object, which is how the Inner object accesses the Outer object’s private fields.
Examples
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
// INNER CLASS
// Notice it is NOT static.
public class AuditSystem {
public void performAudit() {
// The Inner class can access the private 'balance' of the outer class!
if (balance < 0) {
System.out.println("Alert! Account is overdrawn.");
} else {
System.out.println("Account is in good standing.");
}
}
}
public static void main(String[] args) {
// 1. You MUST create the Outer instance first
BankAccount myAccount = new BankAccount(1000);
// 2. Weird syntax: You use the outer instance to create the inner instance
BankAccount.AuditSystem auditor = myAccount.new AuditSystem();
auditor.performAudit();
}
}
Interview Questions
Q: How does an Inner class resolve variable name shadowing?
A: If the Inner class and the Outer class both have a variable with the exact same name, the Inner class variable shadows the Outer one. To access the Outer class variable, you must use the special syntax OuterClassName.this.variableName.
class Outer {
int x = 10;
class Inner {
int x = 20;
void print() {
System.out.println(x); // Prints 20
System.out.println(Outer.this.x); // Prints 10
}
}
}
Q: Can an Inner Class contain static variables or methods?
A: Prior to Java 16, No. Inner classes could not contain static declarations (except for compile-time constant static final primitives). The logic was that since the Inner class is tied to a specific instance, having static class-level variables inside it was philosophically contradictory. However, starting in Java 16, this restriction was removed, and Inner classes can now have static members.