Java Programming - Inner Classes - Discussion

Discussion Forum : Inner Classes - General Questions (Q.No. 7)
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?
MyOuter.MyInner m = new MyOuter.MyInner();
MyOuter.MyInner mi = new MyInner();

MyOuter m = new MyOuter();

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

MyInner mi = new MyOuter.MyInner();
Answer: Option
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.

Discussion:
5 comments Page 1 of 1.

Jeeva said:   4 years ago
No, The inner class is static. Static classes cannot be instantiated. That's the definition of something being 'static'.

Kiko said:   9 years ago
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.

Raja said:   10 years ago
So which one is exact answer guys. I'm confused by looking into your responses.

Khizar said:   1 decade ago
Is option A correct. It doesn't have () for myouter.

I think like the correct answer will be:

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

Shahul said:   1 decade ago
Option B is correct, since inner class is static.

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

Post your comments here:

Your comments will be displayed after verification.