JAVA面向对象练习题——宠物商店

题目:实现一个宠物商店,在商店中有多种(由用户数量确定)宠物,试表示出此种关系,并要求可以根据宠物的关键字查找到相应的宠物信息。所需的宠物信息自行设计。
代码:

package one;
 interface Pet{
  public String getName();
  public String getColor();
  public int getAge();
 }
class Cat implements Pet{
 private String name;
 private String color;
 private int age;
 public Cat(String name,String color,int age){
  this.setName(name);
  this.setColor(color);
  this.setAge(age);
 }
 public void setName(String na){
  this.name=na;
 }
 public void setColor(String color){
  this.color=color;
 }
 public void setAge(int age){
  this.age=age;
 }
 public String getName(){
  return this.name;
 }
 public String getColor(){
  return this.color;
 }
 public int getAge(){
  return this.age;
 }
}
class Dog implements Pet{
 private String name;
 private String color;
 private int age;
 public Dog(String name,String color,int age){
  this.setName(name);
  this.setColor(color);
  this.setAge(age);
 }
 public void setName(String na){
  this.name=na;
 }
 public void setColor(String color){
  this.color=color;
 }
 public void setAge(int age){
  this.age=age;
 }
 public String getName(){
  return this.name;
 }
 public String getColor(){
  return this.color;
 }
 public int getAge(){
  return this.age;
 }
}
class PetShop{
 private Pet pets[];
 private int foot;
 public PetShop(int len){
  if(len>0) {
   this.pets=new Pet[len];
  }
  else{
   this.pets=new Pet[1];
  }
 }
 public boolean add(Pet pet){
  if(this.foot<this.pets.length){
   this.pets[this.foot]=pet;
   this.foot++;
   return true;
  }
  else{
   return false;
  }
 }
 public Pet[] search(String keyword){
  Pet p[]=null;
  int count=0;
  for(int i=0;i<this.pets.length;i++){
   if(pets[i].getName().indexOf(keyword)!=-1||pets[i].getColor().indexOf(keyword)!=-1){
    count++;
   }
  }
  p=new Pet[count];
  int f=0;
  for(int i=0;i<this.pets.length;i++){
   if(pets[i].getName().indexOf(keyword)!=-1||pets[i].getColor().indexOf(keyword)!=-1){
    p[f]=pets[i];
    f++;
   }
  }
  return p;
 }
}
 public class one1{
   public static void main(String[] args) {
    PetShop ps=new PetShop(5);
    ps.add(new Cat("黑猫","黑色",2));
    ps.add(new Cat("花猫","花色",1));
    ps.add(new Dog("黑狗","黑色",2));
    ps.add(new Dog("拉布拉多","黄色",3));
    ps.add(new Dog("金毛","金色",2));
    print(ps.search("黑色"));
   }
   public static void print(Pet p[]){
    for(int i=0;i<p.length;i++)
     System.out.print(p[i].getName()+","+p[i].getColor()+","+p[i].getAge()+"\n");
   }
 }
  

你可能感兴趣的:(JAVA学习)