题目:
实现一个宠物商店的模型,一个宠物商店可以保存多个宠物的信息(主要属性为:名字,年龄),可以实现宠物的上架,下架,模糊查询的功能。
设计分析:
本程序最为重要的就是宠物标准的定义,因为宠物商店需要这个标准,同样,所以可以进入宠物商店销售的宠物也都需要实现这个标准。
1.定义出宠物的标准:
interface Pet {
public String getName() ;
public int getAge() ;
}
本程序定义了一个宠物的接口,可以说这个是宠物商店进行数据保存的标准,而宠物商店并不关心具体的宠物是什么,只关心一点:只要是宠物(实现接口标准),就可以通过宠物商店操作。
2.定义宠物商店:
1.class PetShop {
2. private Link pets = new Link() ;
3. public void add(Pet pet) {
4. this.pets.add(pet) ;
5. }
6. public void delete(Pet pet) {
7. this.pets.remove(pet) ;
8. }
9. public Link search(String keyWord) {
10. Link result = new Link() ;
11. Object obj[] = this.pets.toArray() ;
12. for (int x = 0 ; x < obj.length ; x++) {
13. Pet p = (Pet)obj[x] ;
14. if(p.getName().contains(keyWord)) {
15. result.add(p) ;
16. }
17. }
18. return result ;
}
}
1.定义一个宠物商店的类,因为一个宠物商店要保存多个宠物信息。
2.表示要保存的宠物信息。
3.4.新的宠物类型上架操作,向链表中保存宠物信息。
6.7.宠物下架操作,通过链表删除保存的信息,需要对象比较equals()方法的支持。
9.模糊查询操作,一定返回多个内容,不知道多少个,返回Link即可。keyWord是模糊查询关键字。
10.保存结果。
11.将集合变为对象数组的形式返回,因为集合保存的是Object。
12.13.14.15.向下转型找到具体的宠物对象,如果查询到了,则保存满足条件的结果。
3.定义宠物猫子类:
class Cat implements Pet {
private String name ;
private int age ;
public Cat(String name,int age) {
this.name = name ;
this.age = age ;
}
public boolean equals(Object obj) {
if(this == obj) {
return true ;
}
if(obj == null) {
return false ;
}
if(!(obj instanceof Cat)) {
return false ;
}
Cat c = (Cat)obj ;
if(this.name.equals(c.name) && this.age == c.age) {
return true ;
}
return false ;
}
public String getName() {
return this.name ;
}
public int getAge() {
return this.age ;
}
public String toString() {
return "猫的名字:" + this.name + ",年龄:" + this.age ;
}
}
4.定义宠物狗子类:
class Dog implements Pet {
private String name ;
private int age ;
public Dog(String name,int age) {
this.name = name ;
this.age = age ;
}
public boolean equals(Object obj) {
if(this == obj) {
return true ;
}
if(obj == null) {
return false ;
}
if(!(obj instanceof Cat)) {
return false ;
}
Dog c = (Dog) obj ;
if(this.name.equals(c.name) && this.age == c.age) {
return true ;
}
return false ;
}
public String getName() {
return this.name ;
}
public int getAge() {
return this.age ;
}
public String toString() {
return "狗的名字:" + this.name + ",年龄:" + this.age ;
}
}
5.编写测试类:
public class TestDemo {
public static void main(String args[]) {
PetShop shop = new PetShop() ;
shop.add(new Cat("波斯猫",1));
shop.add(new Cat("短尾猫",2));
shop.add(new Dog("金毛",1));
shop.add(new Cat("拉布拉多",1));
Link all = shop.search("波") ;
Object obj[] = all.toArray() ;
for (int x = 0 ; x<obj.length ; x++) {
System.out.println(obj[x]);
}
}
}
程序执行结果:猫的名字:波斯猫,年龄:1