wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Co variant returns 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 "Co variant returns" Watch "Co variant returns" New topic
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: 6661
    
    5

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 - More SCJP Mocks
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

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: 6661
    
    5

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: 6661
    
    5

oh and thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Co variant returns
 
Similar Threads
constructor up and down hierarchy
doubt -chapter 2 K& B -self test -q no 8
Any one solve it?
Overriding Fragments
Why Is a No-Arg Constructor Required Here?