Instantiating Inner Classes: The Outer.new Syntax
What you'll learn: How to create instances of inner classes using the special outerInstance.new InnerClass() syntax required because inner classes depend on an outer object.
Why Inner Classes Need an Outer Instance
Unlike static nested classes, inner classes have an invisible link to their enclosing outer class instance. Think of an inner class object as being "attached" to a specific outer object—it can't exist independently. This means you can't just use new InnerClass() like you would with a regular class.
The Special Syntax
To create an inner class instance, you must have an outer class instance first, then use this syntax:
Outer outerInstance = new Outer();
Outer.Inner innerInstance = outerInstance.new Inner();
Notice the unusual .new keyword—this tells Java which outer instance the inner object should be bound to.
Example
class Library {
private String name;
class Book {
private String title;
}
}
// Using it:
Library library = new Library();
Library.Book book = library.new Book(); // Correct!
// Library.Book book = new Library.Book(); // ERROR - won't compile
The book object is now permanently linked to that specific library instance.
Inside Methods
If you're already inside an outer class method, you can simply use new Inner() because this is implied:
class Outer {
class Inner { }
void createInner() {
Inner inner = new Inner(); // Same as this.new Inner()
}
}
Key Takeaway: Inner classes require an outer instance to exist; instantiate them using outerInstance.new InnerClass() syntax, which binds the inner object to that specific outer object.