Java Programming - Inner Classes - Discussion

Discussion Forum : Inner Classes - General Questions (Q.No. 6)
6.
class Foo 
{
    class Bar{ }
}
class Test 
{
    public static void main (String [] args) 
    {
        Foo f = new Foo();
        /* Line 10: Missing statement ? */
    }
}
which statement, inserted at line 10, creates an instance of Bar?
Foo.Bar b = new Foo.Bar();
Foo.Bar b = f.new Bar();
Bar b = new f.Bar();
Bar b = f.new Bar();
Answer: Option
Explanation:

Option B is correct because the syntax is correct-using both names (the enclosing class and the inner class) in the reference declaration, then using a reference to the enclosing class to invoke new on the inner class.

Option A, C and D all use incorrect syntax. A is incorrect because it doesn't use a reference to the enclosing class, and also because it includes both names in the new.

C is incorrect because it doesn't use the enclosing class name in the reference variable declaration, and because the new syntax is wrong.

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

Discussion:
4 comments Page 1 of 1.

Kajska said:   1 month ago
Is there would be static Bar then Outer.ineer i = new Outer.ineer(); would be correct.

Gowtham said:   5 years ago
Anyone explain the correct answer.

Ninja said:   8 years ago
I think D is a correct answer. Anybody can explain it?

Subhash said:   9 years ago
A is also a correct answer. While working with inner classes we can create an object based on below syntax.

Outer.ineer i = new Outer.ineer();
(1)

Post your comments here:

Your comments will be displayed after verification.