首先定义老师和学生类,其中设置老师为姓名的设置与获取,类型的String,学生是Integer类
public class Student {
private String name;
public String getName(){
return name;
}
public void setName(String name)
{
this.name=name;
}
}
public class Teacher {
private Integer age;
public Integer getAge(){
return age;
}
public void setAge(Integer age)
{
this.age=age;
}
}
接着定义泛型类,有点类似于c语言的模板
public class Generic<T> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
以下是测试类
public class fanxinglei {
public static void main(String[] args) {
Student s=new Student();
s.setName("林青霞");
System.out.println(s.getName());
Teacher t=new Teacher();
t.setAge(30);
System.out.println(t.getAge());
System.out.println("----------------");
Generic<String> g1=new Generic<>();
g1.setT("林青霞");
System.out.println(g1.getT());
System.out.println("----------------");
Generic<Integer> g2=new Generic<>();
g2.setT(30);
System.out.println(g2.getT());
}
}
以下是运行结果: