思路:
1 定义泛型在类上,来操作不确定的引用数据类型。
这个时候当限定了操作类的引用数据类型1之后,
如果想在使用方法的时候传递引用数据类型2,
就会发生编译失败!
这是泛型类的局限性:
类型一旦确定,就无法使用其他引用数据类型。
泛型类定义的泛型,在整个类中有效,
如果被方法使用,
那么泛型类的对象明确要操作的具体类型后,
所有要操作的类型就已经固定了。
2 为了让不同方法操作不同的类型,
就引入了把泛型定义在方法上的概念。
泛型定义在方法上后,只在方法范围内有效!
- //1 泛型定义在类上,在整个类都有效
- class GenericClass<T>
- {
- public void print(T t)
- {
- System.out.println(t);
- }
- }
- //主类
- class GenericDemo4
- {
- public static void main(String[] args)
- {
- GenericClass<String> gs = new GenericClass<String>();
- gs.print("44h");
- gs.print(new Integer(4));
- }
- }
复制代码
泛型的局限性体现出来了
一旦限定了引用数据类型,就在整个类都有效,
要想使用其他类型,就必须重新建立一个对象
- //2 泛型定义在方法上,只在方法内有效
- class GenericClass<E>
- {
- public <T> void print(T t)//T仅在本方法有效
- {
- System.out.println(t);
- }
- public <E> void show(E e)//跟类走
- {
- System.out.println(e);
- }
- public static <T> void method(T t)//T仅在本方法有效,所以可以重名
- {
- System.out.println(t);
- }
- }
- //主类
- class GenericDemo4
- {
- public static void main(String[] args)
- {
- //静态方法使用泛型
- GenericClass.method("hello");
- GenericClass.method(new Integer(3));
-
- //泛型方法
- GenericClass gs = new GenericClass();
- gs.print("44h");
- gs.print(new Integer(4));
- }
- }
复制代码
特殊之处:
静态方法不可以访问类上定义的泛型。
如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。
|
|