Regarding Method Signature and Overriding

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? 

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: 

class Superclass { 
    int someMethod() { 
        return 123; 
    } 

class Subclass extends Superclass { 
    // Wrongly overridden method 
    String someMethod() { 
        return "Hello"; 
    } 

class Superclass {
    int someMethod() {
  return 123;
 }
}

class Subclass extends Superclass {
 // Wrongly overridden method
 String someMethod() {
  return "Hello";
 }

 

Then look at this: 

Superclass obj = new Subclass(); 

// Do you expect an int or a String here? 
??? result = obj.someMethod(); 
 

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. 

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. 

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.