In Java, consider the following nested type: public class MyOuter { public static class MyInner { public static void foo() { } } } Which statement, when written from some other class (not MyOuter or MyInner), correctly instantiates the static nested class MyOuter.MyInner?

Java Programming Inner Classes Difficulty: Easy
Choose an option
  • A
    MyOuter.MyInner m = new MyOuter.MyInner();
  • B
    MyOuter.MyInner mi = new MyInner();
  • C
    MyOuter m = new MyOuter(); MyOuter.MyInner mi = m.new MyOuter.MyInner();
  • D
    MyInner mi = new MyOuter.MyInner();
  • E
    new MyInner();

Answer

Correct Answer: MyOuter.MyInner m = new MyOuter.MyInner();

Explanation

Introduction / Context:This question tests your understanding of Java static nested classes (also called static member classes) versus inner classes. Knowing when you need an enclosing instance and how to fully qualify the nested type name is essential for compilation and readability.

Given Data / Assumptions:

  • Class MyOuter contains a static nested class MyInner.
  • Code that instantiates MyInner is written in some other class (i.e., outside MyOuter).
  • We must choose the statement that compiles and creates an instance correctly.

Concept / Approach:A static nested class does not require an instance of the enclosing class. It behaves similarly to a top-level class that is scoped within the outer class's namespace. Therefore, you instantiate it with the fully qualified name and the usual new expression, without using an enclosing object reference.

Step-by-Step Solution:

Identify nested type: MyOuter.MyInner is static.Static nested class instantiation syntax: new MyOuter.MyInner().No enclosing instance is needed (unlike non-static inner classes which use outerInstance.new Inner()).Thus the correct statement is: MyOuter.MyInner m = new MyOuter.MyInner();

Verification / Alternative check:If MyInner were non-static, you would need an instance of MyOuter and the syntax would be: MyOuter outer = new MyOuter(); MyOuter.MyInner mi = outer.new MyInner();

Why Other Options Are Wrong:Option B and D omit the outer qualifier for the constructor or type; Option C incorrectly tries to use m.new MyOuter.MyInner(), which is for non-static inner classes; Option E is unqualified and invalid outside the package context without import and still wrong for a nested class.

Common Pitfalls:Confusing static nested with inner classes and attempting to use the outer.new Inner() syntax when the nested class is static.

Final Answer:MyOuter.MyInner m = new MyOuter.MyInner();

Discussion & Comments
No comments yet. Be the first to comment!
More Questions from Inner Classes
Join Discussion