2015-06-15 37 views
0

我有一類獲取錯誤:「構造函數HelloWorld(Float [])含糊不清」爲什麼?

public class HelloWorld { 

    HelloWorld(Float[] a) { 
    } 

    HelloWorld(Double a) { 
    } 
} 

在主程序我這樣做:

public static void main(String args[]) { 
     HelloWorld helloWorld = new HelloWorld(null); 
    } 

和Eclipse顯示「構造的HelloWorld(浮法[])不明確」 爲什麼呢?

+1

相關的http:// stackoverflow。com/questions/30850695/why-java-prefers-to-call-double-constructor/30850736#30850736 – River

+0

你可以試着解釋一下你到底不清楚什麼嗎?兩種方法都接受'空'?你將如何決定哪一個打電話? – Tom

回答

10

原因是null可以被認爲是任何類型。但是,Float[]Double沒有直接關係。 Float[]不是Double的亞型,並且Double不是Float[]的亞型。編譯器會看到兩種適用的方法,但這兩種方法都不比其他方法更具體。在這種情況下,編譯器會生成錯誤,因爲方法調用不明確;它不知道需要調用哪個方法。

Section 4.1 of the JLS狀態:

The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).

In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

此外,Section 15.12.2.5 of the JLS,如何選擇最具體的方法,指出:

It is possible that no method is the most specific, because there are two or more methods that are maximally specific. In this case:

  • If all the maximally specific methods have override-equivalent signatures (§8.4.2), then:

    • If exactly one of the maximally specific methods is concrete (that is, non-abstract or default), it is the most specific method.

    • Otherwise, if all the maximally specific methods are abstract or default, and the signatures of all of the maximally specific methods have the same erasure (§4.6), then the most specific method is chosen arbitrarily among the subset of the maximally specific methods that have the most specific return type.

      In this case, the most specific method is considered to be abstract. Also, the most specific method is considered to throw a checked exception if and only if that exception or its erasure is declared in the throws clauses of each of the maximally specific methods.

  • Otherwise, the method invocation is ambiguous, and a compile-time error occurs.

2

當您嘗試調用函數並且編譯器沒有足夠的信息來確定要調用的方法時,基本上會發生此錯誤。

在你的情況下,當你說new HelloWorld(null)它不知道null是指浮動[]還是Double。

1

當你通過null,你的程序是混淆有關的構造是要調用。因爲這兩個構造函數都只有一個參數。現在它有兩個選擇。

在一般英語中,ambigious意味着你有超過一種不可判定的方式來完成任務。

因此,在編程時,如果遇到歧義,應用程序會崩潰,如果歧義沒有明確處理。

0

Float[]Double之間沒有關係。這就是編譯器模糊不清的原因。 Null可以解釋爲java中的任何引用。

假設你有Float[]Object那麼它會執行Float[]的構造函數。 ObjectFLoat之間有關係。所有包裝類都是Object類的子類。 Float[]應該是更具體的類型。

參考:

Why does Java prefer to call double constructor?

0

null沒有定義類型,這樣你的編譯器不知道哪一個選擇。假裝你是編譯器,你會看到HelloWorld()和HelloWorld()。你選哪一個?希望這會讓你的含混更明顯。

相關問題