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

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

思路:
1 定义泛型在类上,来操作不确定的引用数据类型。
这个时候当限定了操作类的引用数据类型1之后,
如果想在使用方法的时候传递引用数据类型2,
就会发生编译失败!
这是泛型类的局限性:
类型一旦确定,就无法使用其他引用数据类型。
泛型类定义的泛型,在整个类中有效,
如果被方法使用,
那么泛型类的对象明确要操作的具体类型后,
所有要操作的类型就已经固定了。

2 为了让不同方法操作不同的类型,
就引入了把泛型定义在方法上的概念。

泛型定义在方法上后,只在方法范围内有效!
  1. //1 泛型定义在类上,在整个类都有效
  2. class GenericClass<T>
  3. {
  4.         public  void print(T t)
  5.         {
  6.                 System.out.println(t);
  7.         }
  8. }

  9. //主类
  10. class GenericDemo4
  11. {
  12.         public static void main(String[] args)
  13.         {
  14.                 GenericClass<String> gs = new GenericClass<String>();
  15.                 gs.print("44h");
  16.                 gs.print(new Integer(4));

  17.         }
  18. }
复制代码


泛型的局限性体现出来了
一旦限定了引用数据类型,就在整个类都有效,
要想使用其他类型,就必须重新建立一个对象
  1. //2 泛型定义在方法上,只在方法内有效
  2. class GenericClass<E>
  3. {
  4.         public <T> void print(T t)//T仅在本方法有效
  5.         {
  6.                 System.out.println(t);
  7.         }

  8.         public <E> void show(E e)//跟类走
  9.         {
  10.                 System.out.println(e);               
  11.         }

  12.         public  static <T> void method(T t)//T仅在本方法有效,所以可以重名
  13.         {
  14.                 System.out.println(t);
  15.         }
  16. }

  17. //主类
  18. class GenericDemo4
  19. {
  20.         public static void main(String[] args)
  21.         {
  22.                 //静态方法使用泛型
  23.                 GenericClass.method("hello");
  24.                 GenericClass.method(new Integer(3));
  25.                
  26.                 //泛型方法
  27.                 GenericClass gs = new GenericClass();
  28.                 gs.print("44h");
  29.                 gs.print(new Integer(4));


  30.         }
  31. }
复制代码

特殊之处:
静态方法不可以访问类上定义的泛型。
如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马