使用面向对象实现一个宠物商店,在宠物商店中有两种宠物猫咪和狗狗,它们都有三个属性,分别是名字,颜 色,年龄,试表示出此种关系。 2.并再创建一个宠物商店类,再其中声明添加宠物到商店的方法和可以根据宠物的关键字查找到相应的宠物信息的 方法。
时间: 2024-09-19 09:15:51 浏览: 38
用Arduino Uno制作一个智能的自动宠物喂食器(续)-综合文档
3星 · 编辑精心推荐
为了实现这个面向对象的宠物商店,我们可以定义两个宠物基类`Pet`,然后派生出`Cat`和`Dog`子类,每个类都包含名字、颜色和年龄属性。接下来我会展示如何设计类结构以及添加宠物和查找宠物的方法。
首先,我们定义一个`Pet`基类:
```java
public abstract class Pet {
private String name;
private String color;
private int age;
public Pet(String name, String color, int age) {
this.name = name;
this.color = color;
this.age = age;
}
// getter and setter methods for name, color, and age
// Abstract method for printing pet information
public abstract String getPetInfo();
}
```
接着,为`Cat`和`Dog`子类分别实现`getPetInfo()`方法:
```java
public class Cat extends Pet {
@Override
public String getPetInfo() {
return "Name: " + name + ", Color: " + color + ", Age: " + age + " (Cat)";
}
}
public class Dog extends Pet {
@Override
public String getPetInfo() {
return "Name: " + name + ", Color: " + color + ", Age: " + age + " (Dog)";
}
}
```
现在我们定义一个`PetShop`类,该类包含添加宠物和根据关键字查找宠物的方法:
```java
import java.util.HashMap;
import java.util.Map;
public class PetShop {
private Map<String, Pet> pets;
public PetShop() {
this.pets = new HashMap<>();
}
// Method to add a pet to the store
public void addPet(Pet pet) {
pets.put(pet.getName(), pet);
}
// Method to search for a pet by keyword (name)
public Pet findPetByKeyword(String keyword) {
if (pets.containsKey(keyword)) {
return pets.get(keyword);
} else {
throw new IllegalArgumentException("No pet found with that name.");
}
}
}
```
你可以像这样使用这个`PetShop`类:
```java
public static void main(String[] args) {
PetShop shop = new PetShop();
// Add a cat and a dog
Cat cat = new Cat("Fluffy", "White", 3);
Dog dog = new Dog("Max", "Brown", 5);
shop.addPet(cat);
shop.addPet(dog);
// Find pets by name
System.out.println(shop.findPetByKeyword("Fluffy").getPetInfo());
System.out.println(shop.findPetByKeyword("Max").getPetInfo());
}
```
阅读全文