1,泛型的实质是是程序员定义安全的类型。2,ClassCastException异常,“向下转型”操作通常会出现问题,而泛型机制有效的解决了这一问题。
3,下面的例子是泛型的一种应用,对于相加的函数,相加的对象可能是int型,也可能是float型等。通过泛型可以下次解决。
package com.cskaoyan.reflect;
public class ReflectTestMain {
public static void main(String[] args) throws ClassNotFoundException {
//Calc calc =new Calc(1,3);
Calculor<Integer> calculor = new Calculor<Integer>(new Integer(1), 3); //自动装箱
Calculor myCalculor = new Calculor( 1,2);
Object x = myCalculor.getX();
}
//泛型
}
class Calculor<T>{ //此处T必须是类
T x ;
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 Calculor(T x, T y) {
super();
this.x = x;
this.y = y;
}
public Calculor() {
super();
}
}
/*class Calc{
int x;
int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Calc(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class Calc2{
double x;
double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Calc2(double x, double y) {
super();
this.x = x;
this.y = y;
}
}
*/