Java Programming - Inner Classes - Discussion

Discussion :: Inner Classes - General Questions (Q.No.7)


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

MyOuter m = new MyOuter();

MyOuter.MyInner mi = MyOuter.MyInner();

[D]. MyInner mi = new MyOuter.MyInner();

Answer: Option A


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.

Shahul said: (May 6, 2013)  
Option B is correct, since inner class is static.

Object of inner class is not bounded with object of outer class.

Khizar said: (Aug 14, 2015)  
Is option A correct. It doesn't have () for myouter.

I think like the correct answer will be:

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

Raja said: (Nov 30, 2015)  
So which one is exact answer guys. I'm confused by looking into your responses.

Kiko said: (May 17, 2016)  
Option B is the correct answer. Since static nested class , we can directly create instance for inner class object.

It will be,

MyOuter.MyInner mi=new MyInner();

Above must do.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.