就類變量而言,上拋和下鑄有什么區(qū)別?對(duì)于類變量,上拋和下拋有什么區(qū)別?例如,在下面的程序類中,Properties只包含一個(gè)方法,但是Dog類包含兩個(gè)方法,然后我們?nèi)绾螌og變量轉(zhuǎn)換為動(dòng)物變量。如果轉(zhuǎn)換完成了,那么我們?nèi)绾斡脛?dòng)物的變量調(diào)用狗的另一個(gè)方法。class Animal {
public void callme()
{
System.out.println("In callme of Animal");
}}class Dog extends Animal {
public void callme()
{
System.out.println("In callme of Dog");
}
public void callme2()
{
System.out.println("In callme2 of Dog");
}}public class UseAnimlas {
public static void main (String [] args)
{
Dog d = new Dog();
Animal a = (Animal)d;
d.callme();
a.callme();
((Dog) a).callme2();
}}
3 回答

慕斯王
TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
上澆鑄
下播
Dog d = new Dog();Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcastingd.callme();a.callme(); // It calls Dog's method even though we use Animal reference.((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly. // Internally if it is not a Dog object it throws ClassCastException
添加回答
舉報(bào)
0/150
提交
取消