Java中关于int/long和String/object的参数的方法重载 [英] Method overloading in java regarding arguments with int/long and String/object
问题描述
对于以下程序,为什么要调用具有int和String参数的方法而不是long和Object?
For the following program why the methods with int and String arguments are getting called instead of long and Object?
想知道为什么编译器选择long
上的long
和Object
参数上的int.
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);
}
}
推荐答案
对于add(2,3)
方法,您正在传递整数,这就是为什么要调用整数的原因.
对于method(null)
,选择最具体的方法参数.在这种情况下,String
比Object
更具体.因此method(String st);
被调用.
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.
这篇关于Java中关于int/long和String/object的参数的方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!