泛型操作范例

表示一个人的信息
·基本信息
·联系方式
肯定要先定义一个接口,只有实现了接口的类,才能表示出人的信息。
定义一个接口,没有任何方法,称为标识接口,之后定义人的类,人的类中只要是此接口的子类,就可以表示人的信息。
1,首先 定义一个没有内容的接口,即 标识接口,让具体信息子类来实现此接口 去表示人的信息
2,定义子类 实现标识接口 声明 人的信息
3,定义泛型类 T extends Info 指定上限,可以传递任意数据类型

interface Info      //此接口没内容,标识接口,只有此接口的子类才标识人的信息
{
}
class Content implements Info   //定义类 实现接口 表示人的信息
{
    private String address ;    //声明属性 表示地址
    private String tel ;
    public Content(String address,String tel)//构造方法,给属性赋值
    {
        this.setAddress(address) ;
        this.setTel(tel) ;
    }
    public void setAddress(String address)
    {
        this.address = address ;
    }
    public void setTel(String tel)
    {
        this.tel = tel ;
    }
    public String getAddress()
    {
        return this.address ;
    }
    public String getTel() 
    {
        return this.tel ;
    }
    public String toString()  //覆写Object类中的toString()方法
    {
        return "地址:"+this.address+"电话:"+this.tel ;
    }
}
class Introducer implements Info
{
    private String name ;
    private int age ;
    public Introducer(String name,int age)
    {
        this.setName(name) ;
        this.setAge(age) ;
    }
    public void setName(String name)
    {
        this.name = name ;  
    }
    public void setAge(int age)
    {
        this.age = age ;
    }
    public String getName()
    {
        return this.name ;
    }
    public int getAge()
    {
        return this.age ;
    }
    public String toString()
    {
        return "姓名:"+this.name+"年龄:"+this.age ;
    }
}
class Person <T extends Info>       //定义一个人的类 extends Info指定上限,
{
    private T info ; //声明属性     //在方法中定义了泛型操作,则可以传递任意数据类型
    public Person(T info)   //构造方法,设置属性内容
    {
        this.setInfo(info) ;
    }
    public void setInfo(T info)
    {
        this.info = info ;
    }
    public T getInfo()
    {
        return this.info ;
    }
    public String toString() //覆写Object类中的toString()方法
    {
        return this.info.toString() ;
    }
}
public class GenericsDemo10
{
    public static void main(String[] args)
    {
        Person<Content> per = null ;    //声明Person类对象
        per = new Person<Content>(new Content("北京市","海淀区")) ;
        System.out.println(per) ;
        Person<Introducer> per2 = null ;
        per2 = new Person<Introducer>(new Introducer("Iron",20)) ;
        System.out.println(per2) ;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值