多態應用-帶寵物看病案例
阿新 • • 發佈:2018-12-05
div int clas ngui class get ret color take
1 package com.szxs.pet; 2 3 /** 4 * 寵物類 5 */ 6 public abstract class Pet { 7 private int health; 8 9 public int getHealth() { 10 return health; 11 } 12 13 public void setHealth(int health) { 14 this.health = health; 15 } 16 17 public abstract voidtoHospital(); 18 }
1 package com.szxs.pet; 2 3 /** 4 * 狗狗類 5 */ 6 public class Dog extends Pet { 7 /** 8 * 狗狗去醫院 9 */ 10 public void toHospital() { 11 System.out.println("狗狗看病"); 12 } 13 }
1 package com.szxs.pet; 2 3 /** 4 * 企鵝類 5 */ 6 public class Penguin extendsPet { 7 8 /** 9 * 企鵝去醫院 10 */ 11 public void toHospital() { 12 System.out.println("企鵝看病"); 13 } 14 }
1 package com.szxs.pet; 2 3 /** 4 * 主人類 5 */ 6 public class Master { 7 /** 8 * 主人帶寵物去看病 9 * 10 * @author 11 * 12 */ 13 publicvoid taketoHospital(Pet pet) { 14 pet.toHospital(); 15 } 16 }
1 package com.szxs.pet; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 Master m=new Master(); 7 8 m.taketoHospital(new Dog()); 9 m.taketoHospital(new Penguin()); 10 11 } 12 }
多態應用-帶寵物看病案例