基本思想:
使用一个接口作为宠物商店的标准,只要满足接口内的方法都可以实现接口进入宠物商店。本例子用yellVoice()方法作为标准。
导入的类
import java.util.Scanner;//导入Sacnner类
## 接口
interface PetShop{//宠物商店接口
abstract String yellVoice();//接口里面只有一个叫声的方法,只要满足此方法的类,都可以接入宠物商店
}
猫类实现接口
class Cat implements PetShop{//Cat类
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 yellVoice(){//覆写接口方法
return "喵喵喵";
}
public String toString(){
return "(猫)姓名:"+this.name+",颜色:"+this.color+",年龄:"+this.age+",叫声:"+this.yellVoice();
}
}
狗类实现接口
class Dog implements PetShop{//Dog类
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 yellVoice(){//覆写叫声方法
return "汪汪汪";
}
public String toString(){
return "(狗)姓名:"+this.name+",颜色:"+this.color+",年龄:"+this.age+",叫声:"+this.yellVoice();
}
}
其他类实现接口
class Other implements PetShop{//其他类
private String name;
private String color;
private int age;
public Other(String name,String color,int age){
this.name=name;
this.color=color;
this.age=age;
}
public String yellVoice(){//覆写叫声方法,未知
return "未知";
}
public String toString(){
return "(其他)姓名:"+this.name+",颜色:"+this.color+",年龄:"+this.age+",叫声:"+this.yellVoice();
}
}
主加载类,其中有一个setPet()方法,通过这个方法设置相应的宠物类型,使得主方法中的代码量减少**
public class Train{
static Object setPet(String type,String name,String color,int age){//setPet方法,设置实例化接口的对象
if(type.equals("猫")){
return new Cat(name,color,age);//是“猫”就实例化Cat对象
}else if(type.equals("狗")){
return new Dog(name,color,age);//是“狗”就实例化Dog对象
}else{
return new Other(name,color,age);
}
}
public static void main(String args[]){//主方法
System.out.println("请输入宠物的总数:");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
PetShop []p=new PetShop[n];//创建对象数组(相当于在宠物商店开辟空间)
for(int i=0;i<n;++i){
System.out.println("请输入第"+(i+1)+"只宠物类别:");
String type=s.next();
System.out.println("请输入宠物"+type+"的名字:");
String name=s.next();
System.out.println("请输入"+name+"的颜色:");
String color=s.next();
System.out.println("请输入"+name+"的年龄");
int age=s.nextInt();
p[i]=(PetShop)setPet(type,name,color,age);//用PetShop强制转型
}
for(int j=0;j<n;++j){//循环打印宠物商店里的内容(每个类都覆写了toString方法)
System.out.println("第"+(j+1)+"宠物是:"+p[j]);
}
}
}