簡體   English   中英

Ambiguty並沒有找到合適的方法在java重載中發現錯誤

[英]Ambiguty and no suitable method found error in java overloading

假設我有一個像下面這樣的重載類

class Test{
    public void m1(int a,float b){
        System.out.println("hello");
    }
    public void m1(float a,int b){
        System.out.println("hai"); 
    }
    public static void main(String[] args){
        Test t = new Test();
        t.m1(10,10);//error
        t.m1(10.5f,10.6f);//error
    }
}

當我用m1(10,10)兩個int值調用m1()方法時,錯誤是

 error: reference to m1 is ambiguous, both method m1(int,float) in Test and method m1(float,int) in Test match
t.m1(10,10);
 ^

當我用m1(10.5f,10.6f)兩個浮點值調用m1()方法時m1(10.5f,10.6f)錯誤是

error: no suitable method found for m1(float,float)
t.m1(10.5f,10.6f);
 ^
method Test.m1(float,int) is not applicable
  (actual argument float cannot be converted to int by method invocation conversion)
method Test.m1(int,float) is not applicable
  (actual argument float cannot be converted to int by method invocation conversion)

任何人都可以解釋原因,為什么這個程序顯示兩種不同類型的錯誤?

當您嘗試將int參數傳遞給期望float的方法時,該參數可以通過擴展基元轉換自動從int轉換為float (擴展基元轉換不會丟失有關數值整體大小的信息)。 因此,你的方法都可以執行調用t.m1(10,10) ,並且編譯器不能在兩者之間進行選擇(因為兩者都需要將一個參數從int轉換為float ,所以這兩個方法都不是對於給定的參數,它比另一個更合適)。 因此, reference to m1 is ambiguousreference to m1 is ambiguous錯誤。

當你傳遞一個float參數給需要的方法int ,參數不能轉換為int沒有顯式的int ,因為當會有精度損失float被截斷為int 因此,您的方法都不能執行t.m1(10.5f,10.6f)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM