1. 问题
对于一个人,我们可以定义一个信息的属性,但是一个个可能有各种各样的信息(假定只有联系方式和基本信息),怎么将各种各样的信息与人关联起来呢?-->泛型。
2. 代码
1) Info接口
public interface Info {
}
2)Contact.java类
//联系方式来实现Info接口
public class Contact implements Info{
private String address; //联系地址
private String telephone; //联系方式
private String zipcode; //邮政编码
public Contact(String address,String telephone,String zipcode){
this.address=address;
this.telephone=telephone;
this.zipcode=zipcode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String toString(){ //覆写Object方法中的Object方法
return "联系方式:"+"\n" +
"\t|-联系地址:"+this.address+"\n"+
"\t|-联系电话:"+this.telephone+"\n"+
"\t|-邮政编码:"+this.zipcode;
}
}
3) Introduction.java类
//个人基本信息类(包括名字、性别和年龄)
public class Introduction implements Info{
private String name;
private String sex;
private int age;
public Introduction(String name,String sex,int age){
this.name=name;
this.sex=sex;
this.age=age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String toString(){
return "个人基本信息:"+"\n" +
"\t|-姓名:"+this.getName()+"\n"+
"\t|-性别:"+this.getSex()+"\n"+
"\t|-年龄:"+this.getAge();
}
}
4) Person.java类
public class Person<T extends Info> { //定义一个泛型,类型均为Info接口的子类
private T info;
public Person(T info){ //构造方法
this.info=info;
}
public void setInfo(T info) {
this.info = info;
}
public T getInfo() {
return info;
}
public String toString(){ //覆写Object类中的toString()方法
return this.info.toString();
}
}
5) Demo.java类(主方法)
public class Demo {
public static void main(String args[]){
//需要Contact信息
Person<Contact> p1=null;
p1=new Person<>(new Contact("成都市","012-234-456-678","10086"));
System.out.println(p1); //这里是因为覆写了toSting()方法
//需要Introduction信息
Person<Introduction> p2=null;
p2=new Person<>(new Introduction("张三","男",20));
System.out.println(p2);
}
}
3. 运行结果