Hi All
I am reading K&B for SCJP5 exam.
I have a question on Chapter 2 page 168 question 8.
Given:
1. class Plant{
2.
String getName() { return "plant" ;}
3. Plant getType() { return this;}
4. }
5. class Flower extends Plant {
6. //insert code here
7. }
8. class Tulip extends Flower{}
Which statement(s) inserted at line 6, will compile?
Correct Answers given in book are
A) Flower getType() { return this;}
C) Plant getType() { return this;}
D) Tulip getType() { return this ;}
Explanation they gave is
A and D are examples of co-varian returns i.e Flower and Tulip are both subtypes of Plant.
Overridding rule says:
Overriding method must have the same return type ,except that as of Java5 , the return type can be a subclass--this is known as co-variant return.
I think answer C is wrong because it looks to me an illegal override
Please explain the answer D also.
How class Flower can know anything about Tulip class ? As per my knowledge parent classes doesnt know anything about their child classes.
[ October 08, 2007: Message edited by: Yogesh Baraskar ]