All 15 Inner Classes & Anonymous Classes questions
More in Inner Classes & Anonymous Classes
Advertisement
Back to results for “OOP”
Java › Inner Classes & Anonymous Classes

How do you instantiate a non-static inner class from OUTSIDE the enclosing class (from a different class entirely), and what is the exact syntax required?

Beginner

Answer

Instantiating a non-static inner class from outside the enclosing class requires an existing outer instance combined with the special outer.new Inner() syntax (or the fully-qualified OuterClass.InnerClass typeName combined with that same instantiation syntax when referring to the type from elsewhere), since the inner class instance genuinely cannot exist without an associated outer instance to bind to -- this is a notably different, more verbose syntax than instantiating any regular top-level or static nested class, and it's a common source of compile errors for developers unfamiliar with the requirement.
public class Outer {
    class Inner { void greet() { System.out.println("Hello from Inner"); } }
}

// From a different, unrelated class:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();  // requires an existing Outer instance first
inner.greet();

// This would NOT compile: new Outer.Inner();  -- missing the required outer instance
Real-world example A developer new to Java attempting new Outer.Inner() directly (without first creating an Outer instance) encounters a confusing compile error, resolved once they learn the required outer.new Inner() syntax that explicitly ties the new inner instance to a specific, already-existing outer instance.

Common follow-ups: Why does this instantiation requirement not apply to static nested classes, which can be created with simple new Outer.Nested() syntax?;Is there a way to change which specific outer instance an already-created inner class instance is associated with, after the fact?