views:

106

answers:

7

For example can i have something like this:

public static void SAMENAME (sameparameter n) 
{
some code ;
} 

public static String SAMENAME (sameparameter n) 
{
similar code; 
return someString ; 
} 
+3  A: 

This isn't allowed.

The method signature in Java is considered to be the method name and parameter list. The return type is not part of the method signature.

Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.

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

mbaird
+1  A: 

Can't do that. Why do you need to do that?

Raj Kaimal
i have a method that prints a string and i just tried to invoce it as an argument to System.out.println and got the void type not allowed here error. its not a big deal though. 2 lines of code and i've sucesfully dealt with the problem, probobly in a way much more efficent than overleading a method in the way i described. I just thought it would be cool to do it the way i described.
David
+3  A: 

This isn't allowed. For the compiler it is possible that several fit. For instance:

SAMENAME(n);

Could return a String or be void, both are valid.

Thirler
+2  A: 

It's not possible to overload a method on the return type. Have a read of the "Overloading Methods" section on the Java Tutorial.

As it states,

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.

Adrian
+3  A: 

Here's the simplest illustration why you can't. Imagine you implement:

String overloadedMethod();
int overloadedMethod();

and now I call

overloadedMethod();

so, which one gets called ? Since the return type isn't mandated, you can't determine which method to call.

Brian Agnew
Easy. In this theoretical language it would be whatever the LHS is.
Pyrolistical
There is no LHS. Note the 'java' tag on the question.
Brian Agnew
you could have the compiler force a LHS, but then in java your language is weekly typed, what if you have the LHS is char, and you have return short and long, which one do you match? This type of thing could only work in unambiguous way (ie: not having programmer learn arbitrary matching return/LHS matching rules) if it was a strongly typed language and + enforced never ignoring return values
hhafez
A: 

no u cant do that. coz somtimes in java, methods are called ignoring the return value which is known as "method calling for its side-effects."

consider this:

void x(){} int x(){}

x();//method call --allowed in java

how can java determine which x() is called. so overloading based on return types is not allowed in java.

+1  A: 

No, because when the program came across the function call SameName(param n) it would not know which to use.

Grue