[問題] 有關object casting的問題
參考了http://programming.im.ncnu.edu.tw/J_Chapter6.htm
我知道upcasting和downcasting的差異
Animal a1, a2, a3, a4;
Bird b;
Dog d;
Fish f;
a2 = a1 = new Animal();
b = new Bird();
d = new Dog();
f = new Fish();
System.out.println(a1.moveMethod());
System.out.println(b.moveMethod());
System.out.println(d.moveMethod());
System.out.println(f.moveMethod());
a1 = b; // Correct, we call this upcasting
b = a1; // Compile Error, type not compatible
b = (Bird)a1; // downcasting, Compile Correct
a2 = b; // Correct,we call this upcasting
d = a2; // Compile Error, type not compatible
d = (Dog)a2; // Compile Correct, but runtime error
但是我有一個問題,
當我於主程式之內new一個B類別名為b, 且有一個副程式名為show(Object obj)比如
public static void show(Object obj)
{
if( obj instanceof A )//假設有繼承關係為真
{
B newobj= (B)obj;
newobj.show();//假設B類別有show()此方法
}
}
然後在主程式呼叫此副程式show(b), 卻不會有runtime error??
object不是根類別嗎? 為何根類別強制轉型為子類別時(B newobj= (B)obj;)
不會出現runtime error?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.37.76.163
→
03/22 00:10, , 1F
03/22 00:10, 1F
→
03/22 00:17, , 2F
03/22 00:17, 2F
→
03/22 00:21, , 3F
03/22 00:21, 3F
→
03/22 00:23, , 4F
03/22 00:23, 4F
→
03/22 00:30, , 5F
03/22 00:30, 5F
想再請教一下, 為何show(Object obj)可以使用Object接收B類別呢?
※ 編輯: paulcaptain 來自: 114.37.76.163 (03/22 00:34)
推
03/22 00:45, , 6F
03/22 00:45, 6F
→
03/22 00:46, , 7F
03/22 00:46, 7F
→
03/22 00:48, , 8F
03/22 00:48, 8F
→
03/22 00:57, , 9F
03/22 00:57, 9F
推
03/22 01:36, , 10F
03/22 01:36, 10F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):