泛型接口
泛型可以用在类上,也可以用在接口,语法如下:
interface 接口名称<泛型类型>{}
1 package com.fwj.genericsinterfacedemo; 2 3 public interface Demo<T> {//定义泛型类型 4 5 public void print(T param);//抽象方法中使用泛型类型 6 }
下面定义子类实现接口,实现方法有两种:
例子:第一种实现手段
1 package com.fwj.genericsinterfacedemo; 2 3 public class DemoImpl<T> implements Demo<T> { 4 5 @Override 6 public void print(T param) { 7 System.out.println("param:"+param); 8 } 9 10 }
1 package com.fwj.genericsinterfacedemo; 2 3 public class Test { 4 5 6 public static void main(String[] args) { 7 8 DemoImpl<String> demo = new DemoImpl<String>(); 9 demo.print("hello!"); 10 } 11 12 }
例子:第二种实现手段:
1 package com.fwj.genericsinterfacedemo; 2 3 public class DemoImpl implements Demo<DemoImpl> { //设置具体类型 4 5 @Override 6 public void print(DemoImpl param) { 7 System.out.println("param:"+param); 8 } 9 10 }
1 package com.fwj.genericsinterfacedemo; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 7 Demo<DemoImpl> demo = new DemoImpl(); 8 demo.print(new DemoImpl()); 9 } 10 11 }
泛型方法
方法上使用泛型,此方法所在的类不一定是泛型操作类
1 package com.fwj.genericsmethod; 2 3 public class Demo { 4 5 public <T> T print(T param){ //定义泛型方法 6 return param; 7 } 8 }
1 package com.fwj.genericsmethod; 2 3 public class Test { 4 5 6 public static void main(String[] args) { 7 8 Demo demo = new Demo(); 9 System.out.println(demo.print(1));//输入为1表示 类型是Integer 10 } 11 12 }
运行结果:1
方法的返回值定义成泛型数组:
1 package com.fwj.genericsmethod; 2 3 public class Test { 4 5 6 public static void main(String[] args) { 7 8 Integer i[] = func(1,2,3,4,5,6,7,8); 9 for (Integer integer : i) { 10 System.out.println(integer); 11 } 12 } 13 public static <T> T[] func(T...param){ 14 return param; 15 } 16 17 }
泛型的嵌套设置
1 package com.fwj.genericsdemo02; 2 3 public class Info<T> { 4 5 private T param; 6 7 public T getParam() { 8 return param; 9 } 10 11 public void setParam(T param) { 12 this.param = param; 13 } 14 15 }
1 package com.fwj.genericsdemo02; 2 3 public class Person<T> { 4 5 private T info; 6 7 public T getInfo() { 8 return info; 9 } 10 11 public void setInfo(T info) { 12 this.info = info; 13 } 14 15 }
1 package com.fwj.genericsdemo02; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 Person<Info<String>> per = new Person<Info<String>>();//嵌套 7 per.setInfo(new Info<String>()); 8 per.getInfo().setParam("fwj"); 9 System.out.println(per.getInfo().getParam()); 10 } 11 12 }