作者orze04 (orz)
看板java
標題[問題] 關於物件的"="
時間Tue Mar 26 12:31:51 2013
public class QQ {
public static void main(String[] args){
child c1 =
new child();
parent p1 =
new parent();
System.
out.println(p1.toString()+" "+c1.toString());
System.
out.println(
"p1.i: "+p1.i);
p1.show();
System.
out.println(
"c1.i: "+c1.i);
c1.show();
System.out.println(
"");
p1=c1;
System.
out.println(p1.toString()+" "+c1.toString());
System.
out.println(
"p1.i: "+p1.i);
p1.show();
System.
out.println(
"c1.i: "+c1.i);
c1.show();
System.out.println(
"");
}
}
class parent{
int i;
parent(){}
void show(){
System.out.println("show p1.i: "+i);
}
}
class child
extends parent{
int i=1;
child(){}
void show(){
System.out.println("show c1.i: "+i);
}
}
result:
parent@14a55f2 child@15093f1
p1.i: 0
show p1.i: 0
c1.i: 1
show c1.i: 1
child@15093f1 child@15093f1
p1.i: 0
<<~~!?
show c1.i: 1
c1.i: 1
show c1.i: 1
在執行
p1=c1後
透過hashCode可以看到p1和c1已經變成同樣內容
為何要顯示p.i時還是指向parent的class?
還是說
p1=c1只有methodc會被蓋掉,本身成員變數不會?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.136.150.29
推 superlubu:因為 parent.i 之後你又在 child delcare 了自己的 i 03/26 12:39
→ orze04:我的意思是為甚麼p1.i還是0 ? 03/26 12:56
推 popcorny:因為變數同名不會override,而是shadow..Child會有兩份i 03/26 13:18
→ orze04:理解 不過這樣反而有另外一問題 toString到底是怎麼計算的? 03/26 13:28
→ popcorny:toString當然就是因為是同個物件,印出來的資訊當然一樣 03/26 13:56
→ orze04:那既然是同個物件 為何p的i不是1? 03/26 16:51
推 mars90226:p是被當成Parant使用,所以i是0,如果轉型成Child就是1 03/26 17:23
→ orze04:p1=c1後 p1就已經是child了 看hashcode也能證明他是child 03/26 17:54
推 mars90226:我測試轉型了一下沒錯啊... 03/26 19:54
推 sonygood:p1(父)=c1(子)為自動轉型,位置被c1取代了,但是型態為父 03/26 23:13
推 pzyc79:你觀念錯了p1=c1後 你還是要把p1當成Parnat用 因為你是這樣 03/27 16:32
→ pzyc79:宣告的. 寫多型不會考慮到他實體物件... 因為你不可能知道 03/27 16:35