JAVA的多態(強制轉換)


 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM