Overload with different return type in Java? Overload with different return type in Java? java java

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.