Inner Classes

Q1:
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?

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();

ANS:A - MyOuter.MyInner m = new MyOuter.MyInner();

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.



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.