public class Test {
public static void main(String[] args) throws ClassNotFoundException {
new Test().f("dfffg"); // it is running perfectly
new Test().f(1, 1); // it is giving ambiguity
}
public void f(int a,long b){
System.out.println("in int and long");
}
public void f(long a,int b){
System.out.println("in long and int");
}
public void f(String s) {
System.out.println("in String");
}
public void f(StringBuffer o) {
System.out.println("in String bufer");
}
public void f(Object o){
System.out.println("in object");
}
}
当我执行此 new Test().f("dfffg");
时它运行完美,尽管我们有以 StringBuffer 和 Object 作为参数的重载方法
而 f(1,1) 给出了歧义,我可以理解。
最佳答案
new Test().f("dfffg")
匹配 public void f(String s)
和 public void f(Object o )
。当您传递对象参数时,会选择具有最具体参数类型的方法:在本例中为 public void f(String s)
。 String
比 Object
更具体,因为 String
是 Object
的子类。
public void f(StringBuffer o)
与此示例无关,因为 StringBuffer
不是 String
的父类(super class),所以您不能将 String
传递给需要 StringBuffer
的方法。
关于java - 过载 : Ambigutiy while the parameters are primitive but not while it is Reference type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37371148/