admin 管理员组文章数量: 1184232
多态
没有多态时
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 }
转载于:.html
本文标签: 多态
版权声明:本文标题:多态 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1699597805a365198.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论