多態應用-主人與寵物玩耍案例
阿新 • • 發佈:2018-12-05
println 人的 pub spa main 多態 ati eth pla
1 package com.szxs.pet; 2 /** 3 * 寵物類 4 * @author 5 * 6 */ 7 public class Pet { 8 private String name; //姓名 9 private int health; //健康值 10 private int love; //親密度 11 12 public Pet() { 13 } 14 15 public Pet(String name, int health, int love) { 16 this.name = name; 17 this.health = health; 18 this.love = love; 19 } 20 21 public String getName() { 22 return name; 23 } 24 public void setName(String name) { 25 this.name = name; 26 } 27 public int getHealth() { 28 return health; 29 }30 public void setHealth(int health) { 31 this.health = health; 32 } 33 public int getLove() { 34 return love; 35 } 36 public void setLove(int love) { 37 this.love = love; 38 } 39 40 }
1 package com.szxs.pet; 2 3 public class Penguin extends Pet {4 5 public Penguin() { 6 } 7 8 public Penguin(String name, int health, int love) { 9 super(name, health, love); 10 } 11 12 /** 13 * 企鵝南極遊泳 14 */ 15 public void swimming() { 16 System.out.println(this.getName()+"健康值是"+this.getHealth()+",與主人的親密度是"+this.getLove()+",特有能力是南極遊泳"); 17 } 18 }
1 package com.szxs.pet; 2 3 public class Dog extends Pet { 4 5 public Dog() { 6 } 7 8 public Dog(String name, int health, int love) { 9 super(name, health, love); 10 } 11 12 /** 13 * 接飛盤 14 */ 15 public void getFrisbe() { 16 System.out.println(this.getName()+"健康值是"+this.getHealth()+",與主人的親密度是"+this.getLove()+",特有的能力是接飛盤"); 17 } 18 }
1 package com.szxs.pet; 2 3 public class Master { 4 /** 5 * 主人和寵物玩 6 * @author 7 * 8 */ 9 public void play(Pet pet) { 10 11 if(pet instanceof Dog) { 12 Dog dog=(Dog)pet; 13 dog.getFrisbe(); 14 }else if(pet instanceof Penguin) { 15 Penguin p=(Penguin)pet; 16 p.swimming(); 17 } 18 } 19 }
1 package com.szxs.pet; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 Master m=new Master(); 7 m.play(new Dog("歐歐",100,30)); 8 m.play(new Penguin("楠楠",100,50)); 9 } 10 11 }
多態應用-主人與寵物玩耍案例