Can I overload a method to another that accepts the same parameters but has a different return type?

For example, I have something like this:

public static void SAMENAME (sameparameter n) { some code ; } public static String SAMENAME (sameparameter n) { similar code; return someString ; } 
+4
source share
6 answers

This is not allowed.

A method signature in Java is considered as a method name and a list of parameters. The return type is not part of the method signature.

Definition: Two components of a method description include a signature method β€” the name of the method and parameter types.

Source: http://java.sun.com/docs/books/tutorial/java/javaOO/methods.html

+3
source

It is forbidden. For the compiler, it is possible that several are suitable. For instance:

 SAMENAME(n); 

May return String or be invalid, both are valid.

+3
source

Here is a simple illustration of why you cannot. Imagine that you are implementing:

 String overloadedMethod(); int overloadedMethod(); 

and now I call

 overloadedMethod(); 

so what is called? Since the return type is optional, you cannot determine which method to call.

+3
source

Unable to overload method for return type. Read the section called Overload Methods in the Java Tutorial .

As he claims

The compiler does not consider type return when differentiating methods, so you cannot declare two methods using the same signature, even if they have a different return type.

+2
source

No, because when the program came across a call to the SameName (param n) function, he did not know what to use.

+1
source

No, I can’t do it. coz somtimes in java, methods are called ignoring the return value, which is known as the "method that causes its side effects."

consider this:

 void x(){} int x(){} x();//method call --allowed in java 

how to determine java from which x() called. therefore, overloading depending on return types is not allowed in java.

0
source

Source: https://habr.com/ru/post/1305253/


All Articles