package Day11;
public class Test_022 {
public static void main(String[] args) {
Animal1 c = new Cat1();
show(c);
/*Day11.Dog1 cannot be cast to Day11.Cat1 Day11。
狗1不能被扔到Day11.Cat1
Dog1 dd = (Dog1) d;
show(d);*/
Animal1 d = new Dog1();
show(d);
Animal1 p = new Pig1();
show(p);
}
public static void show(Animal1 tmp){//1.进来的是Animal1的引用
tmp.eat();
// Cat1 t = (Cat1) tmp;//(向下转型 )2.转成Cat1的引用
// t.show1();//3.再调Cat1特有的功能
if(tmp instanceof Cat1){//如果tmp进来的是猫就
Cat1 t = (Cat1) tmp;
t.show1();
}else if(tmp instanceof Dog1){//否则 如果进来的是狗就
Dog1 d =(Dog1) tmp;
d.show2();
}else if(tmp instanceof Pig1){
Pig1 p =(Pig1) tmp;
p.show3();
}
}
}
public class Test_022 {
public static void main(String[] args) {
Animal1 c = new Cat1();
show(c);
/*Day11.Dog1 cannot be cast to Day11.Cat1 Day11。
狗1不能被扔到Day11.Cat1
Dog1 dd = (Dog1) d;
show(d);*/
Animal1 d = new Dog1();
show(d);
Animal1 p = new Pig1();
show(p);
}
public static void show(Animal1 tmp){//1.进来的是Animal1的引用
tmp.eat();
// Cat1 t = (Cat1) tmp;//(向下转型 )2.转成Cat1的引用
// t.show1();//3.再调Cat1特有的功能
if(tmp instanceof Cat1){//如果tmp进来的是猫就
Cat1 t = (Cat1) tmp;
t.show1();
}else if(tmp instanceof Dog1){//否则 如果进来的是狗就
Dog1 d =(Dog1) tmp;
d.show2();
}else if(tmp instanceof Pig1){
Pig1 p =(Pig1) tmp;
p.show3();
}
}
}
本文通过一个Java程序示例介绍了多态性的使用,包括如何声明父类引用指向子类对象,并演示了如何利用instanceof关键字进行类型判断及向下转型的方法。

114

被折叠的 条评论
为什么被折叠?



