一,Demo1
public interface Demo <T>{
public void print(T param);
}
public class DemoImpl1<T> implements Demo<T> {
public void print(T param)
{
System.out.print("param="+param);
}
}
public class GenDemo15 {
public static void main(String[] args)
{
Demo<String> demo=new DemoImpl1<String>();
demo.print("hello!");
}
}
二,Demo2
public interface Demo <T>{
public void print(T param);
}
public class DemoImpl2 implements Demo<DemoImpl2>{
public void print(DemoImpl2 param)
{
System.out.print(param);
}
}
public class GenDemo15 {
public static void main(String[] args)
{
//实现泛型接口1
//Demo<String> demo=new DemoImpl1<String>();
//demo.print("hello!");
//实现泛型接口2
Demo<DemoImpl2> demo=new DemoImpl2();
demo.print(new DemoImpl2());
}
}
三,泛型方法
泛型除了在类中定义之外,还可以在方法上定义,而且在方法上使用泛型,此方法所在的类不一定是泛型的操作类。
public class GenDemo2 {
public <T> T print(T param)
{
return param;
}
}
public class GenDemo7 {
public static void main(String args[])
{
GenDemo2 d2=new GenDemo2();
System.out.print(d2.print(1));
Integer i[]=fun(1,2,3,4,5,6);
for(int j:i)
System.out.print(j);
}
public static <T> T[] fun(T...param)
{
return param;
}
}
四,泛型嵌套
public class Info<T> {
public T param;
public T getParam() {
return param;
}
public void setParam(T param) {
this.param = param;
}
}
public class Person<T> {
public T info;
public T getInfo() {
return info;
}
public void setInfo(T info) {
this.info = info;
}
}
public class Test {
public static void main(String args[])
{
Person<Info<String>> per=new Person<Info<String>>();
per.setInfo(new Info<String>());
per.getInfo().setParam("java");
System.out.print(per.getInfo().getParam());
}
}