就类变量而言,上抛和下铸有什么区别?对于类变量,上抛和下抛有什么区别?例如,在下面的程序类中,Properties只包含一个方法,但是Dog类包含两个方法,然后我们如何将Dog变量转换为动物变量。如果转换完成了,那么我们如何用动物的变量调用狗的另一个方法。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贡献1864条经验 获得超2个赞
上浇铸
下播
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
添加回答
举报
0/150
提交
取消