泛型类的概述及使用
A:泛型类概述< T >
B:定义格式
public class 类名<泛型类型1, …> C:注意事项
D:案例演示
package com.heima.bean;
public class Tool<Q> {
private Q q;
public Q getObj() {
return q;
}
public void setObj(Q q) {
this.q = q;
}
}
package com.heima.bean;
public class Student extends Person {
public Student() {
}
public Student(String name, int age) {
super(name, age);
}
}
package com.heima.generic;
import com.heima.bean.Student;
import com.heima.bean.Tool;
import com.heima.bean.Worker;
public class Demo03_Generic {
public static void main(String[] args) {
//泛型就是种瓜得挂,种豆得豆的意思.
//这里你传入一个Student,却用一个Worker接收
//那样就会出现类型转换的异常.
Tool<Student> t = new Tool<>(); //创建工具类对象
t.setObj(new Student("张三", 23));
//Exception in thread "main" java.lang.ClassCastException:
//com.heima.bean.Student cannot be cast to com.heima.bean.Worker
Student w = (Student)t.getObj(); //向下转型
System.out.println(w);
}
}