案例演示: 泛型类的使用
泛型的应用之泛型类: 就是把泛型定义在类上
格式: public class 类名<数据类型 , ....> {}
*/
public class ObjectTools<K> {
private K k ;
public K getK() {
return k;
}
public void setK(K k) {
this.k = k;
}
}
泛型方法的概述和使用
A:泛型方法概述: 把泛型定义在方法上
B:定义格式: public <泛型类型> 返回类型 方法名(泛型类型 变量名)
C:案例演示: 泛型方法的使用
public class Phone {
/**
* 泛型方法
*/
public <E> void show(E e){
System.out.println(e);
}
}
泛型接口的概述和使用
A:泛型接口概述: 把泛型定义在接口上
B:定义格式: public interface 接口名<泛型类型>
C:案例演示: 泛型接口的使用
public interface Inter<T> {
public abstract void show(T t) ;
}
/**
- 泛型接口的子类: 第一种情况: 就是在定义子类的时候我们已经可以明确数据类型了
*/
//public class InterImpl implements Inter<String> {
//
// @Override
// public void show(String t) {
// System.out.println(t);
// }
//
//}
/**
- 泛型接口的子类: 第二种情况: 就是在定义子类的时候我们还不知道到底使用神马数据类型.这个时候我们就需要将这个子类也定义
- 成泛型
*/
public class InterImpl<T> implements Inter<T> {
@Override
public void show(T t) {
System.out.println(t);
}
}
泛型高级之通配符
:泛型通配符<?>: 任意类型,如果没有明确,那么就是Object以及任意的Java类了
B:? extends E: 向下限定,E及其子类
C:? super E: 向上限定,E及其父类
D:案例演示: 泛型高级之通配符的基本使用
/**
* 泛型如果明确了数据类型以后,那么要求左右两边的数据类型必须一致
*/
Collection<Object> col1 = new ArrayList<Object>() ;
Collection<Object> col2 = new ArrayList<Animal>() ;//报错
// ? 表示任意的数据类型
Collection<?> col5 = new ArrayList<Object>() ;
Collection<?> col6 = new ArrayList<Animal>() ;
// ? extends E : 向下限定 , ? 表示的是E或者E的子类
// Collection<? extends Animal> col9 = new ArrayList<Object>() ;//报错
Collection<? extends Animal> col10 = new ArrayList<Animal>() ;
Collection<? extends Animal> col11 = new ArrayList<Dog>() ;
// ? super E: 向上限定 , ? 表示的是E或者E的父类
Collection<? super Animal> col13 = new ArrayList<Object>() ;
Collection<? super Animal> col14 = new ArrayList<Animal>() ;
// Collection<? super Animal> col15 = new ArrayList<Dog>() ;//报错