java - 过载 : Ambigutiy while the parameters are primitive but not while it is Reference type

标签 java string object stringbuffer

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)StringObject 更具体,因为 StringObject 的子类。

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/

相关文章:

string - Tcl 从字符串中取出部分

c++ - 带有引用参数的函数不能处理从其他函数返回的值

java - 通用对象链表 (Java)

javascript - JSON 对象多重过滤器

java - 当用户按下退出键时,如何中断线程并要求其完成工作?

java - 显示普通( double )而不是科学数字 - MVC 应用程序

java - 无法在 Java Spring 中反序列化 JSONObject(在 JSONArray 内部)

java - ListView 到新 Activity,然后使用来自 Hashmap 的 SQLite 数据填充 EditText

字符数组操作

java - 为什么连接两个字符串并将其作为参数传递不会创建新的字符串对象?