1. 程式人生 > >泛型的典型應用:人的資訊類和介面

泛型的典型應用:人的資訊類和介面

interface Info{
}


class Contact implements Info{
private String address;
private String telephone;
private String email;
public Contact(String address, String telephone, String email) {
this.address = address;
this.telephone = telephone;
this.email = email;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
return "Contact [address=" + address + ", telephone=" + telephone
+ ", email=" + email + "]";
}
}


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 String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "基本資訊: [name=" + name + ", sex=" + sex + ", age=" + age
+ "]";
}
}


class Person<T extends Info>{
private T info;
public Person(T info){
this.setInfo(info);
}
public T getInfo() {
return info;
}
public void setInfo(T info) {
this.info = info;
}



public class Test {


public static void main(String[] args) {

Person<Contact> per = null;
per = new Person<Contact>(new Contact("北京","0100000001","111111"));
System.out.println(per.getInfo().toString());

Person<Introduction> per1 = null;
per1 = new Person<Introduction>(new Introduction("李四", "女", 24));
System.out.println(per1.getInfo().toString());


}


}

執行結果:

Contact [address=北京, telephone=0100000001, email=111111]
基本資訊: [name=李四, sex=女, age=24]