Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 920
jenifer Avatar asked Apr 06 '11 04:04

jenifer


People also ask

Can two methods have the same name but different return type?

We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. 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 types.

Can you have 2 methods with the same name in java?

In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading.

Can methods have more than one return type?

A method cannot return more than one type. The signature of a method contains the return type or void if the method doesn't return anything.

Why is it possible to declare two methods with the same name?

Discussion. You can define two methods with the same name so long as they differ in the parameters they accept. One reasons for doing this is one function offers more customization (through parameterization) than the other function.


2 Answers

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.

like image 182
uthark Avatar answered Sep 20 '22 12:09

uthark


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 fine   int doSomething(String s); String doSomething(String s); // this is not 
like image 28
Kaivosukeltaja Avatar answered Sep 18 '22 12:09

Kaivosukeltaja