• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Overriding

 
swaraj gupta
Ranch Hand
Posts: 182
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 182
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 182
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks ...
 
Rohit Ramachandran
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Foo is-a SuperFoo.

Therefore when you're returning a foo, you're returning something that is-a superfoo. Aren't you?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic