This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overridding and co-variant returns query

 
Yogesh Baraskar
Ranch Hand
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
dolly shah
Ranch Hand
Posts: 383
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
C & D are the correct answers. Because in C Flower method overriding the Plant class method as it is. In D Flower class overriding the Plant class method with using co-variant return type(Tulip) since Tulip is also a sublclass of Plant. So both are correct.
 
Yogesh Baraskar
Ranch Hand
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dolly

Thanks for your explanation on answer C.

I still have problem on answer D.

how class Flower will get compiled unless we have class Tulip?

Regards
Yogesh
[ October 08, 2007: Message edited by: Yogesh Baraskar ]
 
dolly shah
Ranch Hand
Posts: 383
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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{}


-At line 8 Tulip class is already declared. Isn't it?
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic