Java Programming - Inner Classes - Discussion

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

2. 

class Boo 
{
    Boo(String s) { }
    Boo() { }
}
class Bar extends Boo 
{
    Bar() { }
    Bar(String s) {super(s);}
    void zoo() 
    {
    // insert code here
    }
}
which one create an anonymous inner class from within class Bar?

[A]. Boo f = new Boo(24) { };
[B]. Boo f = new Bar() { };
[C]. Bar f = new Boo(String s) { };
[D]. Boo f = new Boo.Bar(String s) { };

Answer: Option B

Explanation:

Option B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Bar. Since Bar is a subclass of Boo, it all works.

Option A is incorrect because it passes an int to the Boo constructor, and there is no matching constructor in the Boo class.

Option C is incorrect because it violates the rules of polymorphism—you cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass is not guaranteed to have everything the subclass has.

Option D uses incorrect syntax.


Javac said: (Oct 15, 2013)  
C is incorrect indeed, but not due to polymorphism, but due to invoking it with wrong arguments (String cannot be resolved to a variable). Making it Bar f = new Boo (new String () ) { }; makes it incorrect due to polymorphism.

Pooja said: (Jun 21, 2016)  
Haven't got this yet!

Sami said: (Mar 7, 2017)  
You are absolutely right @Javac.

The argument in Boo should be string reference or value but not a declaration!

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.