多态-----动物的叫声(强制转换)

 

 

没有多态时

 1 package cn.xlf.polymorphism;
 2 
 3 public class Test {
 4     public static void textAnimalVoice(Cat c){
 5         c.voice();
 6     }
 7     public static void textAnimalVoice(Dog c){
 8         c.voice();
 9     }
10     
11     public static void main(String[] args){
12         Cat c = new Cat();
13         textAnimalVoice(c);
14     }
15 
16 }

 

 

 

多态

 

 1 package cn.xlf.polymorphism;
 2 
 3 public class Animal {
 4     public void voice(){
 5         System.out.println("普通动物叫声!");
 6     
 7 }
 8 }
 9 class Cat extends Animal{
10     public void voice(){
11         System.out.println("喵喵喵");
12     }
13     public void catchMouse(){
14         System.out.println("抓老鼠");
15     }
16 }
17 class Dog extends Animal{
18     public void voice(){
19         System.out.println("汪汪汪");
20     }
21     public void seeDoor(){
22         System.out.println("看门狗");
23 }
24     }

 

 

 1 package cn.xlf.polymorphism;
 2 
 3 
 4 public class test02 {
 5     public static void textAnimalVoice(Animal c){//Animal 里面包含了Cat Dog
 6         c.voice();
 7         if(c instanceof Cat){// c是 Cat 的实例对象
 8             ((Cat) c).catchMouse();
 9         }
10 }
11 
12 public static void main(String[] args){
13     Animal c = new Cat();
14     Animal a = new Dog();
15     textAnimalVoice(a);
16     textAnimalVoice(c);
17     
18     Cat a2 = (Cat)c;//强制转换  c 为 Cat
19     a2.catchMouse();;
20 
21 
22 }
23 
24 
25 
26 }

 

 

 

 

转载于:https://www.cnblogs.com/zbgghost/p/8479233.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值