您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
〖第6章:面向对象(高级)〗_实例分析:宠物商店
发布时间:2020-12-17 19:32:14编辑:雪饮阅读()
任务需求:
一个宠物接口不同种类的宠物类继承该接口,并且有另外一个宠物店类在该类中可以添加宠物和搜索宠物,按宠物的名称或者颜色进行搜索。
interface Pet{
abstract public String getName();
abstract public int getAge();
abstract public String getColor();
}
class Cat implements Pet{
private String name;
private String color;
private int age;
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public void setColor(String color){
this.color=color;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getColor(){
return this.color;
}
public Cat(String name,String color,int age){
this.setName(name);
this.setAge(age);
this.setColor(color);
}
}
class Dog implements Pet{
private String name;
private String color;
private int age;
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public void setColor(String color){
this.color=color;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getColor(){
return this.color;
}
public Dog(String name,String color,int age){
this.setName(name);
this.setAge(age);
this.setColor(color);
}
}
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){
int count=0;
for(Pet x:this.pets){
if(x.getName().indexOf(keyword)!=-1 || x.getColor().indexOf(keyword)!=-1){
count++;
}
}
Pet tmp[]=new Pet[count];
for(int x=0;x<this.pets.length;x++){
if(this.pets[x].getName().indexOf(keyword)!=-1 || this.pets[x].getColor().indexOf(keyword)!=-1){
tmp[x]=this.pets[x];
}
}
return tmp;
}
public Pet[] getPets(){
return this.pets;
}
}
public class Hello{
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("拉步拉多","黄色的",3)) ; // 增加宠物,成功
ps.add(new Dog("金毛","金色的",2)) ; // 增加宠物,成功
ps.add(new Dog("黄狗","黑色的",2)) ; // 增加宠物,失败
System.out.println("-----宠物商店的全部宠物------");
printPet(ps.getPets());
System.out.println("-----宠物商店中搜索白色的宠物------");
printPet(ps.search("白"));
}
public static void printPet(Pet pets[]){
for(Pet x:pets){
System.out.println("宠物姓名:"+x.getName()+"\t宠物颜色:"+x.getColor()+"\t宠物年龄:"+x.getAge());
}
}
}
关键字词:java,面向对象