泛型应用小实例

//信息标识接口
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);
    }
}

程序运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值