问题描述:用一个宠物商店的实例描述出面向对象的关系
第一步:接口的设计——>宠物接口(标准)
package com.wang.pet;
public interface Pet {
public String getName();
public int getAge();
public float getPrice();
}
第二步:猫、狗等的实现接口——>实例
猫的实例
package com.wang.pet;
public class Cat implements Pet {
private String name;
private int age;
private float price;
//带参数的构造方法
public Cat(String name, int age, float price) {
super();
this.name = name;
this.age = age;
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setPrice(float price) {
this.price = price;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public float getPrice() {
return price;
}
@Override
public String toString() {
return "宠物猫的名字是:" + name + ", 年龄是:" + age + ", 价格:" + price + "]";
}
}
狗的实例
package com.wang.pet;
public class Dog implements Pet {
private String name;
private int age;
private float price;
public Dog(String name, int age, float price) {
super();
this.name = name;
this.age = age;
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setPrice(float price) {
this.price = price;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public float getPrice() {
return price;
}
@Override
public String toString() {
return "宠物猫的名字是:" + name + ", 年龄是:" + age + ", 价格:" + price + "]";
}
}
第三步:宠物商店的设计(包括了如何存储宠物,增加宠物,模糊查找宠物)
package com.wang.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 Pet[] getPets() {
return this.pets;
}
public boolean add(Pet pet){
if(this.foot<this.pets.length){ //判断宠物商店的宠物是否已满
this.pets[this.foot] = pet;
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){
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){
p[f] = this.pets[i];//将符合条件的宠物保存
f++;
}
}
}
return p;
}
}
第四步:测试
package com.wang.pet;
public class Test {
public static void main(String[] args) {
PetShop ps = new PetShop(6);
ps.add(new Cat("黑小猫",2,38.5f));//增加成功
ps.add(new Cat("黑大猫",5,48.5f));//增加成功
ps.add(new Cat("白小猫",3,26.5f));//增加成功
ps.add(new Cat("白大猫",6,25.5f));//增加成功
ps.add(new Cat("小花猫",4,13.5f));//增加成功
ps.add(new Cat("黑小狗",1,18.5f));//增加成功
ps.add(new Cat("黑大狗",3,31.5f));//增加失败
Pet pets[] = ps.search("小");
for (Pet pet : pets) {
System.out.println(pet.toString());
}
}
}
输出结果:
宠物猫的名字是:黑小猫, 年龄是:2, 价格:38.5]
宠物猫的名字是:白小猫, 年龄是:3, 价格:26.5]
宠物猫的名字是:小花猫, 年龄是:4, 价格:13.5]
宠物猫的名字是:黑小狗, 年龄是:1, 价格:18.5]