泛型:
泛型是为了解决创建多种对象的问题,比如:同时创建 teacher,student, person, family 类,如果写方法,需要每个都对应写一个,泛型的出现解决了这样问题,只需要将类后面加上 <>,里面写上传递的参数类型即可,如下:
泛型在类当中的应用:
package demo01;
public class HelloMethod {
public static void main(String[] args) {
Room<Student> room1 = new Room<>();//想创建学生的对象,只需要让<>里面写上 Student
Room<Teacher> room2 = new Room<>();
Student student = new Student();
room1.set(student);
Teacher teacher = new Teacher();
room2.set(teacher);
}
}
class Room<C>{// 想让老师学生都能用这一个类,只需要将 Room 后面加上 C(什么都行),然后在创建对象的时候确定就好了。
public C c;
public void set(C c) {
this.c = c;
}
}
class Student {
}
class Teacher {
}
泛型在方法当中的使用:
同理,如果想让方法也使用泛型,只需要在返回值类型前面加上 <>,即可。
package demo01;
import java.util.Date;
public class Hello02 {
public static void main(String[] args) {
new Hello02().sayHello(new Date());
}
public <T> void sayHello(T t) {
System.out.println(t);
}
}