Home » Java Programming » Inner Classes

Which statement, if placed in a class other than MyOuter or MyInner, instantiates an instance of the nested class? public class MyOuter { public static class MyInner { public static void foo() { } } }

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

Explanation:

MyInner is a static nested class, so it must be instantiated using the fully-scoped name of MyOuter.MyInner.


Option B is incorrect because it doesn't use the enclosing name in the new.


Option C is incorrect because it uses incorrect syntax. When you instantiate a nested class by invoking new on an instance of the enclosing class, you do not use the enclosing name. The difference between Option A and C is that Option C is calling new on an instance of the enclosing class rather than just new by itself.


Option D is incorrect because it doesn't use the enclosing class name in the variable declaration.


← Previous Question Next Question→

More Questions from Inner Classes

Discussion & Comments

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