babu thannasi wrote:i think its an errata in K&B7 , the answers should be at least E ( line 7 fails to compile). please correct me if i am wrong.
No, you are both times wrong! The book is spot-on! The above code compiles successfully (no compiler errrors). Read on to know why
babu thannasi wrote:1. why line 7 is not failing, i mean compile time . the reason i am thinking this should fail is, because the class Phone3 is not declared abstract.
Why do you think class
Phone3 has to be abstract? It implements the
Device interface which defines the
doIt() method. So in order to be a valid concrete class,
Phone3 has to provide at least an implementation for this method. It can implement this method either directly (implementation defined in the class itself) or indirectly (implementation defined in a class it extends from). Have a look at the code snippet again and I'm sure you'll why class
Phone3 has already an implementation for the
doIt() method.
babu thannasi wrote:2. why line 5 is not failing , again compile time, i thought while over ridding even method signature and return type has to be identical to super class method, in this case, the subclass is allowing a parameter x.
If you want to override a method, you indeed have to use the same parameter list (and the same or a covariant return type). But this is not an override, it's an overload. And overloaded methods must have a different parameter list, so method
doIt(int x) is a valid overload of method
doIt(). So class
Phone2 has 2
doIt methods: one with no parameters and another one with an
int parameter.
Hope it helps!
Kind regards,
Roel