Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i overload a method with another one that takes the same parameters but has a different return type?

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 ; 
} 
like image 342
David Avatar asked Mar 26 '10 20:03

David


People also ask

Can we overload same method with different return type?

No, you cannot overload a method based on different return type but same argument type and number in java.

What happened if two methods have same name same parameters but different return types?

If both methods have same parameter types, but different return type than it is not possible.

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

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. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.

Can overloading be done in two different classes?

Overloading can happen in same class as well as parent-child class relationship whereas overriding happens only in an inheritance relationship.


2 Answers

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

like image 130
Mark B Avatar answered Sep 30 '22 04:09

Mark B


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.

like image 20
Thirler Avatar answered Sep 30 '22 03:09

Thirler