Java泛型
- 泛型的本质是参数化类型,就是将类型由原来具体的类型参数化,然后在调用时传入具体类型
- 泛型类:
public class Student<T> {//定义泛型类 private T t; public void setT(T t) { this.t = t; } public T getT { return t; } } public class Main { public static void main(String[] args) { Student<String> s1 = new Student<String>(); s1.setT("纱雾"); System.out.println(s1.getT()); Student<Integer> s2 = new Student<Integer>(); s2.setT(11); System.out.println(s2.getT()); } }
- 泛型方法:
public class Student { public <T> void show(T t) {//定义泛型方法 System.out.println(t); } } public class Main { public static void main(String[] args) { Student s = new Student(); s.show("纱雾"); s.show(11); } }
- 泛型接口:
public interface Person<T> {//定义泛型接口 void show(T t); } public class Student<T> implements Person<T> {//定义泛型接口的实现类 public void show(T t) { System.out.println(t); } } public class Main { public static void main(String[] args) { Student<String> s1 = new Student<String>(); s1.show("纱雾"); Student<Integer> s2 = new Student<Integer>(); s2.show(11); } }