For the following program why the methods with int and String arguments are getting called instead of long and Object?
Wanted to know why the compiler is choosing int over long and String over Object arguments.
Note: This was asked in an interview.
public class MethodOverloadingTest {
public static void add(int n, int m){
System.out.println("Int method");
System.out.println(n+m);
}
public static void add(long n, long m){
System.out.println("Long method");
System.out.println(n+m);
}
public static void method(String st){
System.out.println("from String method");
}
public static void method(Object obj){
System.out.println("from Object method");
}
/**
* @param args
*/
public static void main(String[] args) {
add(2,3);
method(null);
}
}
解决方案
For the add(2,3) method, you are passing integers, that's why integers are getting called.
For method(null), the most specific method argument is chosen. In this case, String is more specific than Object. Hence method(String st); gets called.