黑马程序员技术交流社区

标题: 6 泛型定义在接口上 [打印本页]

作者: itheima_llt    时间: 2015-4-16 13:20
标题: 6 泛型定义在接口上
  1. /*
  2. 方式一:类继承接口后指定了类型Integer
  3. interface Inter<T>
  4. {
  5.         void show(T t);
  6. }

  7. class InterImpl implements Inter<Integer>
  8. {
  9.         public void show(Integer i)
  10.         {
  11.                 System.out.println(i);
  12.         }
  13. }
  14. class GenericDemo5
  15. {
  16.         public static void main(String[] args)
  17.         {
  18.                 InterImpl i = new InterImpl();
  19.                 i.show(new Integer(88));
  20.         }
  21. }
  22. */

  23. //方式二:类继承接口后,还是不确定引用数据类型,继续使用泛型
  24. interface Inter<T>
  25. {
  26.         <Q>void show(Q q);//泛型定义在方法上,仅仅在方法内有效

  27.         void print(T t);//跟泛型类走
  28. }

  29. class InterImpl<T> implements Inter<T>
  30. {
  31.         public <Q> void show(Q t)//泛型跟方法走
  32.         {
  33.                 System.out.println(t);
  34.         }

  35.         public void print(T t)//泛型跟类走
  36.         {
  37.                 System.out.println("类T:"+t);
  38.         }
  39. }

  40. class GenericDemo5
  41. {
  42.         public static void main(String[] args)
  43.         {
  44.                 InterImpl<String> i = new InterImpl<String>();
  45.                 i.show(new Integer(88));
  46.                 i.show(new String("s88"));
  47.                 i.print(new String("s88"));
  48.                 //i.print(new Integer(88));//编译不能通过
  49.         }
  50. }
复制代码

[attach]68980[/attach]

作者: itheima_llt    时间: 2015-4-16 13:21
所以,泛型定义在方法上是非常有好处的!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2