Day11多态部分-2-1
生活随笔
收集整理的這篇文章主要介紹了
Day11多态部分-2-1
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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();
}
}
}
總結
以上是生活随笔為你收集整理的Day11多态部分-2-1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Day11多态部分-2 【1.2 多态的
- 下一篇: Day11多态部分-3