| Author |
Co variant returns
|
harmeet saini
Ranch Hand
Joined: Apr 11, 2010
Posts: 33
|
|
Hi follwing is the problem from certPal
Given this code snippet, what can be inserted in the fragment ?
And the otipns are
1)return new Object();
2)return this;
3)return new Marmaduke();
4)return null;
5)return"";
the correct options are 2,3,4 and the expalnation given is "Co variant returns are allowed in java language as of JDK1.5
I am not able to understand the explanation and also why option 1 is not correct
Thanks in advance
|
Regards,
Harmeet Singh
|
 |
Deepak Bala
Bartender
Joined: Feb 24, 2006
Posts: 6588
|
|
You cannot return an Object when the expected return type is a subclass of Object.
As for the co-variant return type, of what class type is the instance 'this' ? What is the difference between 'this' and Marmaduke ?
|
SCJP 6 articles - SCJP 5/6 mock exams - SCJP Mocks - SCJP 5 Mock exam (Word document ) - SCJP 5 Mock exam in Java.Inquisition format
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
I don't think this has anything to do with co-variant return types. Its just polymorphism. The return type of go method is Marmaduke, so you cannot return an Object from it. I would be like doing this
(PS: The spelling of otipns is great )
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
Deepak Bala
Bartender
Joined: Feb 24, 2006
Posts: 6588
|
|
I don't think this has anything to do with co-variant return types. Its just polymorphism
Whoops. That is indeed correct. Will make a minor change to the answer's explanation
|
 |
Deepak Bala
Bartender
Joined: Feb 24, 2006
Posts: 6588
|
|
oh and thanks
|
 |
 |
|
|
subject: Co variant returns
|
|
|