Java — Which code fragment allows successful compilation with inner class instantiation? public class Outer { public void someOuterMethod() { //Line 5 } public class Inner { } public static void main(String[] argv) { Outer ot = new Outer(); //Line 10 } }

Difficulty: Medium

Correct Answer: new ot.Inner(); //At line 10

Explanation:


Introduction / Context:
This evaluates knowledge of inner class instantiation rules in Java.



Concept / Approach:
Non-static inner classes require an outer class instance for instantiation. Syntax is: Outer.Inner obj = outerInstance.new Inner();



Step-by-Step:

At Line 5 (inside Outer): "new Inner()" is valid because we are already in the scope of Outer.At Line 10 (static context), we need an Outer instance.So "new ot.Inner()" is valid in main after creating Outer ot = new Outer().


Why Other Options Are Wrong:

  • "new Inner()" at line 10 fails (needs outer reference).
  • "new Outer.Inner()" is valid only if Inner is static.


Final Answer:
new ot.Inner(); //At line 10

Discussion & Comments

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