aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overridding and co-variant returns query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overridding and co-variant returns query" Watch "overridding and co-variant returns query" New topic
Author

overridding and co-variant returns query

Yogesh Baraskar
Ranch Hand

Joined: Oct 07, 2007
Posts: 33
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

Joined: Jun 18, 2007
Posts: 383
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.


SCJP-1.5<br />SCWCD-1.4
Yogesh Baraskar
Ranch Hand

Joined: Oct 07, 2007
Posts: 33
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

Joined: Jun 18, 2007
Posts: 383
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
 
subject: overridding and co-variant returns query
 
Similar Threads
Doubt-Kathy Sierra
K&B doubt
doubt -chapter 2 K& B -self test -q no 8
Question from the scjp book
About return type in JAVA