/*
class Tool
{
private Worker w;
public void setWorker(Worker w)
{
this.w = w;
}
public Worker getWorker()
{
return w;
}
}
*/
class Student
{
}
class Worker
{
}
//泛型前做法
class Tool
{
private Object obj;
public void setObject(Object obj)
{
this.obj = obj;
}
public Object getObject()
{
return obj;
}
}
/*泛型类
什么时候定义泛型类?
当类中要操作的引用类型数据不确定的时候,早起定义Object来完成扩展,现在定义泛型类来完成扩展。
*/
class Utils<QQ>
{
private QQ q;
public void setObject(QQ q)
{
this.q = q;
}
public QQ getObject()
{
return q;
}
}
class GenericDemo3
{
public static void main(String[] args)
{
Utils<Worker> u = new Utils<Worker>();
u.setObject(new Worker());//传入的是Student,编译时提示类型转换异常,提高安全性
Worker w = u.getObject();//不需要强转了,
/*
Tool t = new Tool();
t.setObject(new Worker());//如果传入的是Student,运行时提示类型转换异常ClassCastException
Worker w = (Worker)t.getObject();
*/
}
}
网友评论