【P270】宠物商店代码(各个不同功能的类放在不同的包中定义)
org.lsy.demo.a里的Pet.java
1 package org.lsy.demo.a;2 3 public interface Pet{ // 定义宠物接口4 public String getName() ;5 public String getColor() ;6 public int getAge() ;7 }
org.lsy.demo.b里的Cat.java
1 package org.lsy.demo.b; 2 3 import org.lsy.demo.a.Pet ; 4 5 public class Cat implements Pet{ // 猫是宠物,实现接口 6 private String name ; // 宠物名字 7 private String color ; // 宠物颜色 8 private int age ; // 宠物年龄 9 public Cat(String name,String color,int age){10 this.setName(name) ;11 this.setColor(color) ;12 this.setAge(age) ;13 }14 public void setName(String name){15 this.name = name ;16 }17 public void setColor(String color){18 this.color = color;19 }20 public void setAge(int age){21 this.age = age ;22 }23 public String getName(){24 return this.name ;25 }26 public String getColor(){27 return this.color ;28 }29 public int getAge(){30 return this.age ;31 }32 };
org.lsy.demo.b里的Dog.java
1 package org.lsy.demo.b; 2 3 import org.lsy.demo.a.Pet; 4 5 public class Dog implements Pet{ // 狗是宠物,实现接口 6 private String name ; // 宠物名字 7 private String color ; // 宠物颜色 8 private int age ; // 宠物年龄 9 public Dog(String name,String color,int age){10 this.setName(name) ;11 this.setColor(color) ;12 this.setAge(age) ;13 }14 public void setName(String name){15 this.name = name ;16 }17 public void setColor(String color){18 this.color = color;19 }20 public void setAge(int age){21 this.age = age ;22 }23 public String getName(){24 return this.name ;25 }26 public String getColor(){27 return this.color ;28 }29 public int getAge(){30 return this.age ;31 }32 };
org.lsy.demo.c里的PetShop.java
1 package org.lsy.demo.c; 2 3 import org.lsy.demo.a.Pet; 4 5 public class PetShop{ // 宠物商店 6 private Pet[] pets ; // 保存一组宠物 7 private int foot ; 8 public PetShop(int len){ 9 if(len>0){10 this.pets = new Pet[len] ; // 开辟数组大小11 }else{12 this.pets = new Pet[1] ; // 至少开辟一个空间13 }14 }15 public boolean add(Pet pet){ // 增加的是一个宠物16 if(this.foot
org.lsy.demo.c里的PetShopDemo.java
1 package org.lsy.demo.d; 2 3 import org.lsy.demo.b.Cat; 4 import org.lsy.demo.b.Dog; 5 import org.lsy.demo.a.Pet; 6 import org.lsy.demo.c.PetShop; 7 8 public class PetShopDemo{ 9 public static void main(String args[]){10 PetShop ps = new PetShop(5) ; // 五个宠物11 ps.add(new Cat("白猫","白色的",2)) ; // 增加宠物,成功12 ps.add(new Cat("黑猫","黑色的",3)) ; // 增加宠物,成功13 ps.add(new Cat("花猫","花色的",3)) ; // 增加宠物,成功14 ps.add(new Dog("拉步拉多","黄色的",3)) ; // 增加宠物,成功15 ps.add(new Dog("金毛","金色的",2)) ; // 增加宠物,成功16 ps.add(new Dog("黄狗","黑色的",2)) ; // 增加宠物,失败17 print(ps.search("黑")) ;18 }19 public static void print(Pet p[]){20 for(int i=0;i