wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
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
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3064
    
  33

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
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

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?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Method Overriding
 
Similar Threads
regarding doStuff()
covariant doubt
method overriding
Overloaded method
covariant data types and overloaded method