下面的代码是对泛型类里面,因为父类访问子类属性的限制,而产生的对数据类型转换和数据存取方法的逐步优化过程。
public class TestTemplate {
public static void main(String[] args) {
/**
* F a=new F(new Student(111,"lisi",'m'),30.5);
* System.out.println(a.getB().getName);
*/
//父类只能访问子类里面父类定义的属性,
//而Object类里面没有name属性。
//那么我们可以这样做:
/**
* F a=new F(new Student(111,"lisi",'m'),30.5);
* Student o = (Student) a.getB();
* System.out.println(o.getName());
*/
//但是,转换也比较浪费时间和空间。
//下面我们可以这样做:
//我们定义类的时候,不确定类里面放什么数据类型。
//但是,一旦我们使用的时候,
//系统就把数据类型给我们确定了。
//我们先把类的参数属性定义一下:
/**
* public F<S,T> {
* this.b = b;
* this.c = c;
* }
*
* public S getB() {
* return b;
* }
*
* public void setB(S b) {
* this.b = b;
* }
*
* public T getC() {
* return c;
* }
*
* public void setC(T c) {
* this.c = c;
* }
*
* private S b;
* private T c;
*/
//我们现在传参的时候可以这样做:
/**
* F<Student,Double> a=new F(new Student(111,"lisi",'m'),30.5);
* Student o = a.getB();
* System.out.println(o.getName());
*/
//现在我们在调用的时候,因为有了泛型,
//我们的get方返回的就是我们想要得到的类型,
//即在我们使用的时候就确定了。
//所以就没有强制转换这一步了。
//下面是在泛型归则下输出的Integer类型和Double型数据
/**
* F<Integer, Double> a = new F<>(20, 30.34);
* System.out.println(a.getB());
* System.out.println(a.getC());
*/
}
}