JAVA的多型(強制轉換)
阿新 • • 發佈:2018-11-11
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 }