除了用到了泛型,还用到了<T extends Info>来设定上限。看实例:
interface Info{//只有此接口的子类才能表示人的信息
}
class Person<T extends Info>{ //为参数T设置一个上限,必须是Info或Info的子类。
private T info;
/*
构造函数
*/
public Person(T info){
this.info=info;
}
public void setInfo(T info){
this.info=info;
}
public T getInfo(){
return this.info;
}
public String toString(T info){
return this.info.toString();
}
}
class Contact implements Info{ //表明Contact是Info的子类,他可以使用在Person中
private String address;
private String telphone;
private String zipcode;
/*
构造函数
*/
public Contact(String address,String telphone,String zipcode){
this.address=address;
this.telphone=telphone;
this.zipcode=zipcode;
}
public void setAddress(String address){
this.address=address;
}
public String getAddress(){
return this.address;
}
public void setTelphone(String telphone){
this.telphone=telphone;
}
public String getTelphone(){
return this.telphone;
}
public void setZipcode(String zipcode){
this.zipcode=zipcode;
}
public String getZipcode(){
return this.zipcode;
}
public String toString(){
return "联系方式:" + "\n" +
"\t|- 联系电话:" + this.telphone + "\n" +
"\t|- 联系地址:" + this.address + "\n" +
"\t|- 邮政编码:" + this.zipcode ;
}
}
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 this.name;
}
public void setSex(String sex){
this.sex=sex;
}
public String getSex(){
return this.sex;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return this.age;
}
public String toString(){
return "基本信息:" + "\n" +
"\t|- 姓名:" + this.name + "\n" +
"\t|- 性别:" + this.sex + "\n" +
"\t|- 年龄:" + this.age ;
}
}
public class ExampleFanxing{
public static void main(String[] args){
Person<Contact> p=null;
Person<Introduction> p1=null;
Contact c = new Contact("110","北三环东路","100029");
Introduction i= new Introduction("武开英","男",22);
p = new Person<Contact>(c);
p1=new Person<Introduction>(i);
System.out.print(p.getInfo().toString());
System.out.print(p1.getInfo().toString());
}
}
class Person<T extends Info>{}表明了Person类的上限,只能是Info或Info的子类。类Contact和Introduction继承了接口Info,满足条件。
如果去掉Contact类中的implements Info会出现如下错误:
E:\JAVA\NotePadJava\Demo1>javac ExampleFanxing.java
ExampleFanxing.java:100: 错误: 类型参数Contact不在类型变量T的范围内
Person<Contact> p=null;
^
其中, T是类型变量:
T扩展已在类 Person中声明的Info
ExampleFanxing.java:104: 错误: 类型参数Contact不在类型变量T的范围内
p = new Person<Contact>(c);
^
其中, T是类型变量:
T扩展已在类 Person中声明的Info
2 个错误