编写一个宠物类Pet,属性:id,name,health,love;重写父类toString()方法,两个子类狗狗和猫类,狗狗有品种(strain),猫类有爱好(hobby),重写父类toString()方法,宠物饿了,需要主人给宠物喂食,狗狗吃狗粮,猫咪吃小鱼,吃完后健康值狗狗增加3,猫咪增加5
时间: 2023-09-05 14:11:24 浏览: 86
好的,以下是宠物类Pet和其子类狗狗类Dog和猫类Cat的代码实现:
```
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 feed() {
// 默认宠物吃完后健康值增加2
this.health += 2;
}
@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;
}
public void feed() {
// 狗狗吃狗粮,健康值增加3
this.setHealth(this.getHealth() + 3);
}
@Override
public String toString() {
return "Dog{" +
"id=" + this.getId() +
", name='" + this.getName() + '\'' +
", health=" + this.getHealth() +
", love=" + this.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;
}
public void feed() {
// 猫咪吃小鱼,健康值增加5
this.setHealth(this.getHealth() + 5);
}
@Override
public String toString() {
return "Cat{" +
"id=" + this.getId() +
", name='" + this.getName() + '\'' +
", health=" + this.getHealth() +
", love=" + this.getLove() +
", hobby='" + hobby + '\'' +
'}';
}
}
```
在基类Pet中定义了属性和方法,子类Dog和Cat继承了基类Pet,并在继承的基础上增加了品种和爱好属性,并分别重写了feed()和toString()方法。其中,feed()方法根据宠物的不同,增加对应的健康值;toString()方法返回宠物的属性值。
在使用中,可以根据需要创建Pet、Dog或Cat对象,并调用feed()方法喂食,调用toString()方法获取宠物的属性值。例如:
```
Pet pet = new Pet(1, "小白", 80, 70);
pet.feed();
System.out.println(pet.toString());
Dog dog = new Dog(2, "旺财", 90, 80, "哈士奇");
dog.feed();
System.out.println(dog.toString());
Cat cat = new Cat(3, "小花", 85, 90, "捉迷藏");
cat.feed();
System.out.println(cat.toString());
```
输出结果为:
```
Pet{id=1, name='小白', health=82, love=70}
Dog{id=2, name='旺财', health=93, love=80, strain='哈士奇'}
Cat{id=3, name='小花', health=90, love=90, hobby='捉迷藏'}
```
可以看到,宠物的健康值根据不同的类型增加了不同的值,toString()方法返回了宠物的属性值。
阅读全文