Can two Java methods have same name with different return types? [duplicate] Can two Java methods have same name with different return types? [duplicate] java java

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


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.


Only, if they accept different parameters. If there are no parameters, then you must have different names.

int doSomething(String s);String doSomething(int); // this is fineint doSomething(String s);String doSomething(String s); // this is not


According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {    public static void main(String... args) {        Main.<Integer>print();        Main.<Short>print();        Main.<Byte>print();        Main.<Void>print();    }    public static <T extends Integer> int print() {        System.out.println("here - Integer");        return 0;    }    public static <T extends Short> short print() {        System.out.println("here - Short");        return 0;    }    public static <T extends Byte> byte print() {        System.out.println("here - Byte");        return 0;    }    public static <T extends Void> void print() {        System.out.println("here - Void");    }}

Prints

here - Integerhere - Shorthere - Bytehere - Void

For more details, read my article here