Reputation: 2253
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);
}
}
Upvotes: 0
Views: 3416
Reputation: 121998
The concept is called as Early Binding. Most specific method (based on arguments) is Chosen at compile time.
Object
is the least specific than any other class in java, Since it is the super class of all.
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
How it chooses is given in rule set, Specified here
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5
Upvotes: 1
Reputation: 993
Its simple because Java treats number by default as int and letters as string object , not as generic objects .
so when you pass add(2,3) , its taking the arguments as the normal int
to call the add(long , long) pass the arguments as ; add(2.0,4.0) something like this . and for calling the function method(object)
1.first typecast your string to type object String str; str= (object) "Hello world";
2.and then pass to method(str);
Upvotes: 1
Reputation: 13556
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.
Upvotes: 5