Can two Java methods have same name with different return types?

jenifer picture jenifer · Apr 6, 2011 · Viewed 129.9k times · Source

Can two Java methods have the same name with different return type? The return type of the methods are different and they are declared with the same method's name.

Is that allowed?

Answer

uthark picture uthark · Apr 6, 2011

If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java SE 8 Edition, ยง8.4.2. Method Signature:

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (ยง8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

If both methods has different parameter types (so, they have different signature), then it is possible. It is called overloading.