码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA的多态(强制转换)

时间:2018-10-18 00:56:59      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:name   end   调用   强制类型转换   xtend   ring   黄色   str   extends   

 1 abstract class Animal {
 2     String name;
 3     String color;
 4 
 5     public Animal(String name, String color) {
 6         this.name = name;
 7         this.color = color;
 8     }
 9 
10     public abstract void run();
11 }
12 
13 class Dog extends Animal {
14 
15     public Dog(String name, String color) {
16         super(name, color);
17     }
18 
19     public void run() {
20         System.out.println(color + name + "四条腿跑");
21     }
22 
23     public void find() {
24         System.out.println(color + name + "找骨头");
25     }
26 }
27 
28 class fish extends Animal {
29 
30     public fish(String name, String color) {
31         super(name, color);
32     }
33 
34     public void run() {
35         System.out.println(color + name + "游的快");
36     }
37 
38     public void eat() {
39         System.out.println(color + name + "吃面包屑");
40     }
41 }
42 
43 public class Demo {
44     public static void main(String[] args) {
45         // Animal a = new fish("小鱼", "黄色");
46         // 强制类型转换就能调用到子类的方法
47         // fish f = (fish) a;
48         // f.eat();
49 
50         fish f = new fish("小鱼", "黄色");
51         printThe(f);
52         Dog d = new Dog("小狗", "花的");
53         printThe(d);
54     }
55 
56     // 定义一个函数接收任意类型的动物对象,在函数内部调用动物特有的方法
57     public static void printThe(Animal a) {
58         if (a instanceof fish) {
59             fish f = (fish) a;
60             f.eat();
61         } else if (a instanceof Dog) {
62             Dog d = (Dog) a;
63             d.find();
64         }
65     }
66 }

 

JAVA的多态(强制转换)

标签:name   end   调用   强制类型转换   xtend   ring   黄色   str   extends   

原文地址:https://www.cnblogs.com/ronle/p/9807438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!