aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Method Overriding" Watch "Method Overriding" New topic
Author

Method Overriding

swaraj gupta
Ranch Hand

Joined: Oct 22, 2010
Posts: 181



This code compiles successfully, why?
As whatever i know if sub class overrides a super class method then the return type of overriding method must be same as what of overridden method of super class (Compile time error otherwise). Please help
Mohamed Sanaulla
Bartender

Joined: Sep 08, 2007
Posts: 2925
    
  15

swaraj gupta wrote:

This code compiles successfully, why?
As whatever i know if sub class overrides a super class method then the return type of must be same as what in super class (Compile time error otherwise). Please help


Its using CoVariant Return type. You can return either the same type or sub class of that type. So in this case Foo extends SuperFoo, so where ever a SuperFoo instance is expected we can assign a Foo instance.
Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 422
Hi Swaraj, Could you please set the status as Yes for "Allow other users to send private messages:" in your My Profile page. I want to send a Private Message (PM)
swaraj gupta
Ranch Hand

Joined: Oct 22, 2010
Posts: 181

thanks mohammed sanaullah,

just one more thing to ask...i have tried this snippet and found that along with what you have said
we can return null as well from the overriding doStuff method of class Foo, may i have the reason for this.. ...
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9189
    
    2

swaraj gupta wrote:i have tried this snippet and found that along with what you have said
we can return null as well from the overriding doStuff method of class Foo, may i have the reason for this.. ...

null can be type casted into any reference type, so you can return null from any method which returns an object i.e. anything except a primitive...
swaraj gupta
Ranch Hand

Joined: Oct 22, 2010
Posts: 181

thanks ...
Rohit Ramachandran
Ranch Hand

Joined: Oct 05, 2010
Posts: 102
Foo is-a SuperFoo.

Therefore when you're returning a foo, you're returning something that is-a superfoo. Aren't you?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Method Overriding
 
Similar Threads
Overloaded method
covariant doubt
method overriding
regarding doStuff()
covariant data types and overloaded method