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 }