将第六章的宠物商店代码中各个不同功能的类放在不同的包中定义,一定要严格遵循命名规范的要求。

 

package PetShop.Pet.Cat;
import PetShop.Pet.*;
public class Cat extends Pet{
	private String name;
	private String color;
	private int age;
	public Cat(String name,String color,int age){
		this.name=name;
		this.color=color;
		this.age=age;
	}
	public String getName(){
		return this.name;
	}
	public String getColor(){
		return this.color;
	}
	public int getAge(){
		return this.age;
	}
}

  

package PetShop.Pet.Dog;
import PetShop.Pet.*;
public class Dog extends Pet{
	private String name;
	private String color;
	private int age;
	public Dog(String name,String color,int age){
		this.name=name;
		this.color=color;
		this.age=age;
	}
	public String getName(){
		return this.name;
	}
	public String getColor(){
		return this.color;
	}
	public int getAge(){
		return this.age;
	}
}

  

package PetShop.Pet;
public abstract class Pet{
	public abstract String getName();
	public abstract String getColor();
	public abstract int getAge();
}

  

package PetShop;
import PetShop.Pet.*;
public 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(this.pets[i]!=null){
				if(this.pets[i].getName().indexOf(keyWord)!=-1||this.pets[i].getColor().indexOf(keyWord)!=-1){
					count++;
				}
			}
		}
		p=new Pet[count];
		int f=0;
		for(int i=0;i<this.pets.length;i++){
			if(this.pets[i]!=null){
				if(this.pets[i].getName().indexOf(keyWord)!=-1||this.pets[i].getColor().indexOf(keyWord)!=-1){
					p[f]=this.pets[i];
					f++;
				}
			}
		}
		return p;
	}
}

  

package PetShop;
import PetShop.*;
import PetShop.Pet.*;
import PetShop.Pet.Dog.*;
import PetShop.Pet.Cat.*;
public class PackPetShop{
	public static void main(String args[]){
		PetShop ps = new PetShop(5) ;	// 五个宠物
		ps.add(new Cat("白猫","白色的",2)) ;	// 增加宠物,成功
		ps.add(new Cat("黑猫","黑色的",3)) ;	// 增加宠物,成功
		ps.add(new Cat("花猫","花色的",3)) ;	// 增加宠物,成功
		ps.add(new Dog("金毛","金色的",2)) ;	// 增加宠物,成功
		ps.add(new Dog("黄狗","黑色的",2)) ;	// 增加宠物,失败
		print(ps.search("黑")) ;
	}
	public static void print(Pet p[]){
		for(int i=0;i<p.length;i++){
			if(p[i]!=null){
				System.out.println(p[i].getName() + "," + p[i].getColor()
					+"," + p[i].getAge()) ;
			}
		}
	}
}

  

posted on 2017-10-11 11:09  煮咖啡的猪!  阅读(239)  评论(0编辑  收藏  举报