wood burning stoves 2.0*
The moose likes Java in General and the fly likes Question regarding method signature and overriding. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Question regarding method signature and overriding." Watch "Question regarding method signature and overriding." New topic
Author

Question regarding method signature and overriding.

Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 443
    
    1

Hello,

Methods cannot be overloaded based on the return types alone. That makes sense as the compiler will not be in a position to differentiate which method is invoked.

In the case of overriding something similar is applicable. Why cannot a method which is overriding in a derived class not permitted to have a different return type? The compiler will be able to make out the overriding method but then why does it care about the return types matching?

Cheers,
Raj.

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14111
    
  16

Because of polymorphism. You could have a variable of the type of the superclass which actually refers to an instance of the subclass. Suppose you could do this:

Then look at this:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Miklos Szeles
Ranch Hand

Joined: Oct 21, 2008
Posts: 142
Jesper is absolutely right. Just one note:
From Java 5 you can use covariant return types.
It means that a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Which can be of great use in methods like clone(). For instance, Date.clone() could have returned a Date, thereby removing the need for casts. Sun however were either lazy or they simply forgot to change the declared return types for just about every method that could have used it. It's not like returning Date from Date.clone() would have broken any code, it just would have made all the casts unnecessary.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 443
    
    1

Thanks everyone!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Question regarding method signature and overriding.