1.泛型类
public class Holder<T> {
T a;
public Holder(T a) {
this.a = a;
}
public static void main(String[] args) {
new Holder<Shape>(new Circle());///只能存入Shape或者是其子类
/////new Holder<Circle>(new Shape()); 编译错误
}
}
class Shape{
void fun(){
System.out.println("Shape");
}
}
class Circle extends Shape{
@Override
void fun() {
System.out.println("Circle");
}
}
2.泛型方法
public class GenericMethod {
public <T> T f(T x){
return x;
}
public <T> String v(T x){
return x.getClass().getName();
}
public <T> List<T> asList(T... args) {
List<T> list = new ArrayList<>();
for(T t:args){
list.add(t);
}
return list;
}
public static void main(String[] args) {
GenericMethod g = new GenericMethod();
g.f("fuck"); //////自动类型推断,自动推断只会发生在赋值操作
g.<String>f("you"); /////显式类型说明,一般不用
List<String> list = g.asList("I fuck you".split(" ")); ////可变参数与泛型方法
System.out.println(list);
System.out.println(g.v(1));
}
}
3.擦除