//信息标识接口
interface Info{
}
//联系方式信息类
class Contact implements Info{
private String mobile;
private String address;
public Contact(String mobile, String address) {
this.mobile = mobile;
this.address = address;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "联系方式:" +
"mobile='" + mobile + '\'' +
", address='" + address ;
}
}
//个人信息
class Introduction implements Info{
private String name;
private int age;
public Introduction(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "个人信息:" +
"name='" + name + '\'' +
", age=" + age ;
}
}
class Person<T extends Info>{ //指定类型上限,必须是Info接口的子类
private T info;
public Person(T info) {
this.info = info;
}
public T getInfo() {
return info;
}
public void setInfo(T info) {
this.info = info;
}
@Override
public String toString() {
return this.info.toString();
}
}
public class GenericsDemo31 {
public static void main(String[] args) {
Person<Contact> p1 = new Person<Contact>(new Contact("123456789","广州市")); //需要不同信息传入不同类
System.out.println(p1);
Person<Introduction> p2 = new Person<Introduction>(new Introduction("张三",20)); //需要不同信息传入不同类
System.out.println(p2);
}
}
程序运行结果: