泛型应用

泛型应用

interface UserInfo{ // 定义一个标示接口,此接口没有任何方法

}

// 定义一个标示信息的类--->联系方式
class Contact implements UserInfo {
    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 String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTelphone() {
        return telphone;
    }

    public void setTelphone(String telphone) {
        this.telphone = telphone;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    @Override
    public String toString() {
        return "Contact{" +
                "address='" + address + '\'' +
                ", telphone='" + telphone + '\'' +
                ", zipcode='" + zipcode + '\'' +
                '}';
    }
}

// 信息类--->个人基本信息
class Introduction  interface UserInfo{
    private String name;
    private int age;
    private String sax;

    public Introduction(String name, int age, String sax) {
        this.name = name;
        this.age = age;
        this.sax = sax;
    }

    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;
    }

    public String getSax() {
        return sax;
    }

    public void setSax(String sax) {
        this.sax = sax;
    }

    @Override
    public String toString() {
        return "Introduction{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sax='" + sax + '\'' +
                '}';
    }
}

// 定义Person类,Person类中的UserInfo属性的类型使用泛型

class Persons<T extends UserInfo>{ // 向上转型,必须是UserInfo 的子类
    private T userInfo;

    public Persons(T userInfo) {
        this.userInfo = userInfo;
    }

    public T getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(T userInfo) {
        this.userInfo = userInfo;
    }

    @Override
    public String toString() {
        return "Persons{" +
                "userInfo=" + userInfo +
                '}';
    }
}



package com.wanggs.generic;

/**
 * Created by wanggs on 2017/7/26.
 */
public class Test {
    public static void main(String[] args) {
        Person person = new Person<Contact>(new Contact("杭州","120","3242"));
        System.out.println(person);

        Person person1 = new Person<Introduction>(new Introduction("tom",12,"sex"));
        System.out.println(person1);
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容