[英]Why is int implicitly cast to float rather than double when invoking constructor?
我寫了這個測試代碼
public class ConstructorTestApplication {
private static String result;
public static void main(String[] args) {
ConstructorTest test1 = new ConstructorTest(0);
System.out.println(result);
}
private static class ConstructorTest {
public ConstructorTest(double param){
result = "double constructor called!";
}
public ConstructorTest(float param) {
result = "float constructor called!";
}
}
}
結果是
float constructor called!
為什么調用float構造函數而不是雙構造函數? 這是動態方法查找的一部分嗎?
ConstructorTest(float param)
是兩個構造函數中最具體的方法,因為帶有double
參數的方法可以接受任何float
值,但反之則不然。
15.12.2.5。 選擇最具體的方法
如果多個成員方法都可訪問並適用於方法調用,則必須選擇一個為運行時方法調度提供描述符。 Java編程語言使用選擇最具體方法的規則。
非正式的直覺是, 如果第一個方法處理的任何調用都可以傳遞給另一個沒有編譯時類型錯誤的調用,那么一個方法比另一個方法更具體 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.