1.需求 :java编写一个宠物类Pet,属性: id,name,health,love ;重写父类toString()方法 o两个子类狗狗和猫类,狗狗有品种(strain),猫类有爱好(hobby),重写父类toString()方法 o宠物饿了,需要主人给宠物喂食,狗狗吃狗粮、猫咪吃小鱼,吃完之后健康值狗狗增加3,猫咪增加5。
时间: 2024-02-24 21:00:09 浏览: 196
java源码宠物
好的,下面是代码实现:
```java
public class Pet {
private int id;
private String name;
private int health;
private int love;
public Pet(int id, String name, int health, int love) {
this.id = id;
this.name = name;
this.health = health;
this.love = love;
}
public void eat() {
System.out.println(name + " is eating.");
if (this instanceof Dog) {
health += 3;
} else if (this instanceof Cat) {
health += 5;
}
}
@Override
public String toString() {
return "Pet{" +
"id=" + id +
", name='" + name + '\'' +
", health=" + health +
", love=" + love +
'}';
}
}
public class Dog extends Pet {
private String strain;
public Dog(int id, String name, int health, int love, String strain) {
super(id, name, health, love);
this.strain = strain;
}
@Override
public String toString() {
return "Dog{" +
"id=" + getId() +
", name='" + getName() + '\'' +
", health=" + getHealth() +
", love=" + getLove() +
", strain='" + strain + '\'' +
'}';
}
}
public class Cat extends Pet {
private String hobby;
public Cat(int id, String name, int health, int love, String hobby) {
super(id, name, health, love);
this.hobby = hobby;
}
@Override
public String toString() {
return "Cat{" +
"id=" + getId() +
", name='" + getName() + '\'' +
", health=" + getHealth() +
", love=" + getLove() +
", hobby='" + hobby + '\'' +
'}';
}
}
```
以上代码定义了Pet类和两个子类Dog和Cat。Pet类中定义了id、name、health、love四个属性和eat()方法。eat()方法用于宠物吃东西,根据宠物类型不同,增加健康值也不同。Dog类和Cat类分别继承了Pet类,Dog类中定义了strain属性,Cat类中定义了hobby属性。同时,两个子类分别重写了父类的toString()方法,用于输出宠物的属性。
阅读全文