Day11多态部分-2-1

来源:互联网 发布:2016詹姆斯总决赛数据 编辑:程序博客网 时间:2024/06/04 19:28
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();
}
}
}