泛型的典型应用:人的信息类和接口

本文通过具体的Java代码示例介绍了如何使用泛型来创建更灵活的类,并展示了如何实现接口以提供特定的功能实现。具体包括联系信息类和基本介绍类的设计,以及它们在Person泛型类中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值