说的简单一点,所谓的泛型指的就是:在类定义的时候并不会设置类中的属性或方法中的参数的具体类型,而是在类使用的时候在进行定义。
所以如果要想进行这种泛型的操作,就必须做一个类型标记的声明。
范例:定义Point类
class Point <T>{//T表示参数,是一个占位的标记 private T x; private T y; public T getX() { return x; } public void setX(T x) { this.x = x; } public T getY() { return y; } public void setY(T y) { this.y = y; } }
public class TestDemo { public static void main(String[] args) { //第一步:设置数据 Point <String>p=new Point<>();//JDK1.7 JDK1.5 p.setX("东经10度"); }
当开发的程序可以避免向下转型,也就意味着这种安全隐患呗消除了。
尽量不要去使用向下转型。
这一切的目的都是为了回避ClaClassCastException
文章来源: 泛型的基本使用