C泛型(泛型实现)
一、泛型的基本使用
所谓的泛型指的就是在类定义的时候并不会设置类中的属性或方法中的参数的具体类型,而是在类使用时候在进行定义。
所以如果要想进行这种泛型的操作,就必须做一个类型标记的声明。
二、范例:定义Point类
Package cn.mldn.demo;
//在Point类定义的时候完全不知道x和y的属性是什么类型,而由使用者来
class Point <T> { //T表示参数,是一个占位的标记
private T x ;
private T y ;
public T grtX() {
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<String>();
p.setX(“东经10度”); // 设置坐标
p.setY(“北纬10度”);
//第二步:取出数据
String x =p.getX() ; //避免了向下转型
String y =p.getY() ; //避免了向下转型
System.out.println(“x=”+x+“y=”+y)
}
当开发的程序可以避免向下专享也就意味着这种安全隐患被消除了。尽量不要去使用向下转型。