public class MyOuter {
    public static class MyInner {
        public static void foo() {}
    }
}

which statement, if placed in a class other than MyOuter or MyInner, instantiates an instance of the nested class?

  1. MyOuter.MyInner m = new MyOuter.MyInner();

  2. MyOuter.MyInner mi = new MyInner();

  3. MyOuter m = new MyOuter(); MyOuter.MyInner mi = m.new MyOuter.MyInner();

  4. MyInner mi = new MyOuter.MyInner();


Correct Option: A

AI Explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) MyOuter.MyInner m = new MyOuter.MyInner(); This option is correct because it instantiates an instance of the nested class MyInner by using the fully qualified name MyOuter.MyInner.

Option B) MyOuter.MyInner mi = new MyInner(); This option is incorrect because it tries to instantiate an instance of the nested class MyInner without using the fully qualified name MyOuter.MyInner. Since this statement is placed in a class other than MyOuter or MyInner, the nested class cannot be accessed directly without using the outer class name.

Option C) MyOuter m = new MyOuter(); MyOuter.MyInner mi = m.new MyOuter.MyInner(); This option is incorrect because it creates an instance of the outer class MyOuter. It then tries to create an instance of the nested class using the new keyword and the outer class name MyOuter, but this is not the correct syntax to instantiate a static nested class.

Option D) MyInner mi = new MyOuter.MyInner(); This option is incorrect because it tries to instantiate the nested class MyInner using the outer class name MyOuter, which is not the correct syntax for accessing a static nested class. Additionally, since this statement is placed in a class other than MyOuter or MyInner, the nested class cannot be accessed directly without using the outer class name.

The correct answer is A. This option instantiates an instance of the nested class MyInner by using the fully qualified name MyOuter.MyInner.

Find more quizzes: