1.写一个宠物类Pet,属性:id name health love;重写父亲类toString()方法 2.两个子类狗类和猫类,狗狗有品种(strain),猫类有爱好(hobby),重写父类TOString()方法 3.宠物饿了,需要主人给宠物喂食,狗狗吃狗粮,猫咪吃小鱼.吃完之后健康值狗狗增加3,猫咪增加5
时间: 2024-02-24 15:59:23 浏览: 75
好的,这是三个问题,我分别回答:
1. 宠物类Pet的代码如下:
```java
public class Pet {
protected int id;
protected String name;
protected int health;
protected int love;
public Pet(int id, String name, int health, int love) {
this.id = id;
this.name = name;
this.health = health;
this.love = love;
}
@Override
public String toString() {
return "Pet{" +
"id=" + id +
", name='" + name + '\'' +
", health=" + health +
", love=" + love +
'}';
}
}
```
2. 狗类和猫类的代码如下:
```java
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=" + id +
", name='" + name + '\'' +
", health=" + health +
", love=" + love +
", 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=" + id +
", name='" + name + '\'' +
", health=" + health +
", love=" + love +
", hobby='" + hobby + '\'' +
'}';
}
}
```
3. 给宠物喂食的代码如下:
```java
public class Main {
public static void main(String[] args) {
Dog dog = new Dog(1, "旺财", 80, 90, "哈士奇");
Cat cat = new Cat(2, "咪咪", 70, 80, "玩线球");
System.out.println(dog);
System.out.println(cat);
feed(dog, "狗粮");
feed(cat, "小鱼");
System.out.println(dog);
System.out.println(cat);
}
public static void feed(Pet pet, String food) {
if (pet instanceof Dog && food.equals("狗粮")) {
pet.health += 3;
} else if (pet instanceof Cat && food.equals("小鱼")) {
pet.health += 5;
}
}
}
```
注意,这里的feed方法中,我们使用了instanceof运算符来判断宠物是狗还是猫。当宠物是狗且喂食的是狗粮时,健康值增加3;当宠物是猫且喂食的是小鱼时,健康值增加5。最后我们打印出喂食后的宠物信息。
阅读全文