Java — Create an instance of a non-static member inner class from outside its outer class: class Foo { class Bar { } } class Test { public static void main (String [] args) { Foo f = new Foo(); /* Line 10: Missing statement? */ } }

Difficulty: Easy

Correct Answer: Foo.Bar b = f.new Bar();

Explanation:

Introduction / Context:This tests knowledge of instantiating a non-static member inner class. Such a class requires an instance of the outer class to create the inner instance, and its type name must be qualified with the outer class name.

Given Data / Assumptions:

  • Foo has a non-static inner class Bar.
  • In Test.main, we already have Foo f = new Foo().

Concept / Approach:Syntax for member inner class instantiation is: OuterClass.InnerClass var = outerInstance.new InnerClass(); The unqualified InnerClass name is not visible at top level; you must use the qualified type.

Step-by-Step Solution:

Use Foo.Bar as the type on the left-hand side.Use f.new Bar() to bind the new inner instance to the existing Foo instance f.Therefore: Foo.Bar b = f.new Bar();

Verification / Alternative check:Trying new Foo.Bar() without an instance fails because Bar is not static; trying Bar b = f.new Bar() fails because Bar is not in scope without Foo qualification.

Why Other Options Are Wrong:

  • new Foo.Bar() requires Bar to be static; it is not.
  • Bar b = ... uses an unqualified type name that is not visible.
  • new f.Bar() is invalid syntax; f is a variable, not a type.

Common Pitfalls:Forgetting the outer instance requirement and the qualified type name for non-static inner classes.

Final Answer:Foo.Bar b = f.new Bar();

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion