Can we have same method name with different return type?

Can we have same method name with different return type?

You can not define more than one method with the same name, Order and the type of the arguments. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile-time error.

What if 2 functions in a class have same name and input parameters but different return types will it work?

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.

Can different classes have the same method name?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. Normally the constructor name and class name always the same in Java.

What is it called when more than one function has the same name?

Definition: Two or more functions can have the same name but different parameters; such functions are called function overloading. C++ has many features, and one of the most important features is function overloading. It is a code with more than one function with the same name having various types of argument lists.

When do method names need to be the same?

@Divine – When overloading the method names must be the same, but the parameter lists must be different. They can differ in the types and/or the number of parameters. The don’t need to have the same return type, it’s just that overload resolution is done only on the parameters of a method, not the return type.

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

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. See: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

Why are method names and parameters different in Java?

The combination of the method name and the parameter list. This happens because it is not possible for the jvm two choose between to methods that differs only from the return type. The jvm infact can investigate only the name of the method and the type of parameters of the call. So your example is not possible in java.

Can a method have the same signature as another method?

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.