java重載時自動轉換咋回事?舉例說明
當一個重載的方法被調用時,Java在調用方法的參數和方法的自變量之間尋找匹配。 (視頻下載) (全部書籍)
但是,這種匹配並不總是精確的。只有在找不到精確匹配時,Java的自動轉換才會起作用。 (如果定義了test(int),當然先調用test(int)而不會調用test(double)。 )
本章源碼
//自動類型轉換 Automatic type conversions() apply to overloading.
class Overl {
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
public class Test {
public static void main(String args[]) {
Overl ob = new Overl();
int i = 80;
ob.test(i); // 沒有int類型,所以調用double類型的自動轉換。this will invoke test(double)
ob.test(555.5); // 準確調用,this will invoke test(double)
ob.test(5, 8);//準確調用
}
}
result結果 is:
Inside test(double) a: 80.0
Inside test(double) a: 555.5
a and b: 5 8
Assignment: practice overload, make two methods,add(int a,int b), add(int a,int b,int c)
詳情請進:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner2_web.html#AutomaticConversion
java重載時自動轉換咋回事?舉例說明