Java多态练习
1· 创建一个Pet类
public abstract class Pet {
private int health;
public Pet(){
}
public Pet (int health){
this.health = health;
}
public int getHealth(){
return health;
}
// 判断健康值
public void setHealth(int health) {
this.health = health;
if (this.health > 100){
this.health = 100;
System.out.println("吃不下了,要消化一下");
}
}
//抽象
public abstract void eat(String food);
}
2·创建狗狗和企鹅
public class Dog extends Pet{ //继承父类
public Dog(int health){
super(health);
}
@Override
public void eat(String food) {
System.out.println("狗狗的初始健康值:" + getHealth() + ",狗狗想吃" + food + ";狗狗吃到了" + food + ",健康值加3");
setHealth(getHealth()+3);
}
}
public class Penguin extends Pet{
public Penguin(int health){
super(health);
}
@Override
public void eat(String food) {
System.out.println("企鹅的初始健康值:" + getHealth() + ",企鹅想吃" + food + ";企鹅吃到了" + food + ",健康值加5");
setHealth(getHealth()+5);
}
}
3·新增小猫
public class Cat extends Pet{
public Cat(int health){
super(health);
}
@Override
public void eat(String food) {
System.out.println("小猫的初始健康值:" + getHealth() + ",小猫想吃" + food + ";小猫吃到了" + food + ",健康值加4");
setHealth(getHealth()+4);
}
}
public class Person {
//吃东西
public void feed(Pet pet,String food){
pet.eat(food);
String f = food;
}
public static void main(String[] args) {
//给宠物喂食
Person person = new Person();
Pet dog = new Dog(82);
person.feed(dog,"狗粮");
System.out.println("狗狗吃完后的健康值是" + dog.getHealth());
Pet penguin = new Penguin(60);
person.feed(penguin,"鱼");
System.out.println("企鹅吃完后的健康值是" + penguin.getHealth());
Pet cat = new Cat(84);
person.feed(cat,"鲜鱼");
System.out.println("小猫吃完后的健康值是" + cat.getHealth());
}
}