ani ani - 28 days ago 13
Java Question

Overloading or a normal method

I am gonna put this question to have a clear idea about overloading Concept in java . As per my understanding while method resolution in overloading compiler will look for method signature that is it should have same method name and different argument types . But what if the return type is different ??

class Test{
public void m1(int i) {
System.out.println(" int arg");
}

public int m1(String s) {
System.out.println("String-arg");
return (5+10);
}

public static void main (String[] args) throws java.lang.Exception
{
Test t = new Test();
t.m1(5);
int i = t.m1("ani");
System.out.println(i);
}}


the above program is running perfectly . my doubt here is , the method m1() is it overloaded ?? it has different return type . someone please make it clear. Thanks in advance

Answer

In Java methods are identified by name and arguments' classes and amount. The return type doesn't identify the method. For this reason the following code would be illegal:

public void m1(String i) {

    System.out.println(" int arg");
}

public int m1(String s) {

    System.out.println("String-arg");
    return (5+10);
}

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded. (...) When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4)

Summarizing, two methods with the same name can return different types, however it's not being taken into account when deciding which method to call. JVM first decides which method to call and later checks if the return type of that method can be assigned to the certain variable.

Example (try to avoid such constructions):

public int pingPong(int i) {
    return i;
}
public String pingPong(String s) {
    return s;
}
public boolean pingPong(boolean b) {
    return b;
}