Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload with different return type in Java?

You can't do it in Java, and you can't do it in C++. The rationale is that the return value alone is not sufficient for the compiler to figure out which function to call:

public int foo() {...}
public float foo() {..}

...
foo(); // which one?

The reason is that overloads in Java are only allowed for methods with different signatures.

The return type is not part of the method signature, hence cannot be used to distinguish overloads.

See Defining Methods from the Java tutorials.


Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.


Overloaded methods in java may have different return types given that the argument is also different.

Check out the sample code.

public class B {

    public String greet() {
        return "Hello";
    }

    //This will work
    public StringBuilder greet(String name) {
        return new StringBuilder("Hello " + name);
    }

    //This will not work
    //Error: Duplicate method greet() in type B
    public StringBuilder greet() {
        return new StringBuilder("Hello Tarzan");
    }

}

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.