[問題] 關於物件的"="是什麼概念?

看板java作者 (orz)時間12年前 (2013/03/26 12:31), 編輯推噓6(607)
留言13則, 6人參與, 最新討論串1/2 (看更多)
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

03/26 12:39, , 1F
因為 parent.i 之後你又在 child delcare 了自己的 i
03/26 12:39, 1F

03/26 12:56, , 2F
我的意思是為甚麼p1.i還是0 ?
03/26 12:56, 2F

03/26 13:18, , 3F
因為變數同名不會override,而是shadow..Child會有兩份i
03/26 13:18, 3F

03/26 13:23, , 4F
http://goo.gl/nCsjy google到的文章
03/26 13:23, 4F

03/26 13:28, , 5F
理解 不過這樣反而有另外一問題 toString到底是怎麼計算的?
03/26 13:28, 5F

03/26 13:56, , 6F
toString當然就是因為是同個物件,印出來的資訊當然一樣
03/26 13:56, 6F

03/26 16:51, , 7F
那既然是同個物件 為何p的i不是1?
03/26 16:51, 7F

03/26 17:23, , 8F
p是被當成Parant使用,所以i是0,如果轉型成Child就是1
03/26 17:23, 8F

03/26 17:54, , 9F
p1=c1後 p1就已經是child了 看hashcode也能證明他是child
03/26 17:54, 9F

03/26 19:54, , 10F
我測試轉型了一下沒錯啊...
03/26 19:54, 10F

03/26 23:13, , 11F
p1(父)=c1(子)為自動轉型,位置被c1取代了,但是型態為父
03/26 23:13, 11F

03/27 16:32, , 12F
你觀念錯了p1=c1後 你還是要把p1當成Parnat用 因為你是這樣
03/27 16:32, 12F

03/27 16:35, , 13F
宣告的. 寫多型不會考慮到他實體物件... 因為你不可能知道
03/27 16:35, 13F
文章代碼(AID): #1HKIIxsX (java)
文章代碼(AID): #1HKIIxsX (java)