宠物饿了,主人需要为宠物喂食,使用多态实现该过程
不同宠物吃的东西不一样
不同宠物吃完东西后恢复健康值不一样
健康值达到100时,不需要继续喂食
创建一个Matser类
public class Master { public void feed(Pet pet, String food){ pet.eat(food); } } 12345
再创建一个Pet父类
public class Pet { private int healthy; public Pet(int healthy) { this.healthy = healthy; } public Pet() { } public void eat(String food){ System.out.println("宠物吃"+food); } public int getHealthy() { return healthy; } public void setHealthy(int healthy) { this.healthy = healthy; if (this.healthy>100){ this.healthy=100; System.out.println("宠物已经吃饱了,不能再喂了"); } } }
123456789101112131415161718192021222324252627创建Dog子类
public class Dog extends Pet { public Dog(int healthy) { super(healthy); } public Dog() { } @Override public void eat(String food) { System.out.println("狗狗吃"+food+",吃饱后健康值加3"); setHealthy(getHealthy()+3); } } 1234567891011121314
创建Penguin子类
public class Penguin extends Pet { public Penguin(int healthy) { super(healthy); } public Penguin() { } @Override public void eat(String food) { System.out.println("企鹅吃"+food+",吃饱后健康值加5"); setHealthy(getHealthy()+5); } } 1234567891011121314
创建测试类
public class Test { public static void main(String[] args) { Master m = new Master(); Dog dog = new Dog(60); m.feed(dog,"骨头"); System.out.println(dog.getHealthy()); Penguin penguin = new Penguin(50); m.feed(penguin,"鱼"); System.out.println(penguin.getHealthy()); } } 1234567891011121314