java重載時自動轉(zhuǎn)換咋回事
當(dāng)一個重載的方法被調(diào)用時,Java在調(diào)用方法的參數(shù)和方法的自變量之間尋找匹配。
但是,這種匹配并不總是精確的。只有在找不到精確匹配時,Java的自動轉(zhuǎn)換才會起作用。 (如果定義了test(int),當(dāng)然先調(diào)用test(int)而不會調(diào)用test(double)。 )
馬克- to-win:馬克 java社區(qū):防盜版實名手機(jī)尾號: 73203。
本章源碼
//自動類型轉(zhuǎn)換 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類型,所以調(diào)用double類型的自動轉(zhuǎn)換。this will invoke test(double)
ob.test(555.5); // 準(zhǔn)確調(diào)用,this will invoke test(double)
ob.test(5, 8);//準(zhǔn)確調(diào)用
}
}
result結(jié)果 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)
3.一個對象可能有多個參考(One Object can have many Reference)
AClass one = new AClass();one就是這個對象的參考,有點(diǎn)類似指針的概念。指向生成的對象。java中不叫pointer,叫reference。為什么叫參考 呢?比如在我的書中我說,你要不懂,可以參考一下abc那本書,順著我的指引,你就知道世界上還有abc這本書。悟出"參考"和指針之間的關(guān)系了嗎?
本章源碼
class PointClass {
int length;
void setLength(int n) {
length = n;
}
int getLength() {
return length;
}
}
public class Test {
public static void main(String[] args) {
PointClass p1 = new PointClass();//p1指向生成的對象。
PointClass p2 = p1;//p2指向p1
PointClass p3 = new PointClass();//p3是新的
p1.setLength(10);
System.out.println("p1: " + p1.getLength());
System.out.println("p2: " + p2.getLength());
System.out.println("p3: " + p3.getLength());
}
}
result is:
p1: 10
p2: 10
p3: 0