Overload with different return type in Java?

Solution 1:

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?

Solution 2:

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.

Solution 3:

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.

Solution 4:

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");
    }

}