java 調用方法引起歧義:The method XXX is ambiguous for the type XX

The method XXX is ambiguous for the type XX

eclipse編譯報錯。

分析原因:方法歧義,是編譯器無法確定,代碼中使用哪一個方法。

1、調用的是自己編寫的方法

public class Ambiguous {
    public static void main(String[] args) {
        Ambiguous ambiguous = new Ambiguous();
        ambiguous.Para(null);
    }

    public void Para(String a) {
        System.out.println("String類型a" + a);
    }

    public void Para(StringBuffer a) {
        System.out.println("StringBuffer" + a.toString());
    }
}

顯然null作爲參數,會導致編譯器無法識別調用哪一個方法。

這種情況,有一種特例是,如果方法的參數有繼承關係,那麼編譯器可以確定調用哪個方法,確定的原則是”我要的,你都有“。

2、調用庫方法。

有些庫靜態方法很多靜態字段很多,爲了方便調用調用,常常這樣寫:

import static org.csdn.linghushaoxia.Demo.*;
<pre name="code" class="java">import static org.csdn.linghushaoxia.Demo1.*;


如果,碰巧在別的包裏面,存在相同的方法,可就麻煩了,不容易查找。

比如,調用了Demo.init()靜態方法,代碼裏直接就寫init();

在Demo1裏面有Demo1.init(),代碼裏再直接寫init();必然引起歧義了。

在查出歧義之後,就好解決了,加上包就可以了。

這樣子:

org.csdn.linghushaoxia.Demo.init();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章