public class MyOuter { public static class MyInner { public static void foo()…
2024
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?
(Assume no import statement for MyInner exists in that other class.)
- A.
MyOuter.MyInner m = new MyOuter.MyInner();
- B.
MyOuter.MyInner mi = new MyInner();
- C.
MyOuter m = new MyOuter();
MyOuter.MyInner mi = m.new MyInner();
- D.
MyInner mi = new MyOuter.MyInner();
Attempted by 5 students.
Show answer & explanation
Correct answer: A
A static nested class belongs to its enclosing class itself, not to any instance of it. Code outside both the outer and the nested class must reference the nested class through the outer class's name, and must construct it with new OuterClass.NestedClass() -- no outer-class instance is created or required to do this.
Here, MyInner is declared static inside MyOuter. From a class other than MyOuter or MyInner, both the declared type and the constructor call must therefore carry the MyOuter qualifier: MyOuter.MyInner m = new MyOuter.MyInner(); compiles cleanly because every reference to the nested class is fully qualified with its enclosing class name.
Contrasting the other statements shows why each one fails:
MyOuter.MyInner mi = new MyInner(); -- the declared type carries the outer-class qualifier, but the constructor call drops it and uses the bare name MyInner. Outside MyOuter, that bare name is not visible without an import, so this line does not compile.
MyOuter m = new MyOuter(); MyOuter.MyInner mi = m.new MyInner(); -- the instance.new Inner() form exists only for a non-static inner class that needs a living outer instance to attach to. A static nested class carries no such requirement and is never created through an outer object, so this syntax is invalid here.
MyInner mi = new MyOuter.MyInner(); -- the constructor call is fully qualified, but the declared type on the left is the bare name MyInner, which -- like the previous case -- is not resolvable from outside MyOuter without an import.
Only the statement that qualifies both the declared type and the constructor call with MyOuter compiles from outside the enclosing class.