A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© itheima_llt 高级黑马   /  2015-4-16 13:20  /  391 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  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. }
复制代码


1 个回复

倒序浏览
所以,泛型定义在方法上是非常有好处的!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马