泛型:
Object obj = new Integer(30);
相当于父引用指向子对象就是多态
public class ObjectTool{
private object obj;
public Object getobj()
{
return obj;
}
public void setObj(Object obj)
{
this.obj = obj;
}
}
public class ObjectsToolDemo{
public static void main (String [] agrs){
ObjectTool ot = new ObjectTool();
//使用1
ot.setObj(new Integer(2));
Integer i = (Integer) ot.getObj();
System.out.println(i);
ot.setObj(new String("haha"));
String s = (String) ot.getObj();
System.out.println(s);
//classcastException
ot.setObj(new Integer(11));
String q = (String) ot.getObj();
System.out.println(q);
}
}
向上转型没有问题,但是向下转型的时候其实隐含啦类型转换问题
也就是说这样的程序并不是安全的,所以在JDK5之后引入啦泛型,提高安全性
public class ObjectTool<T>{
private T obj;
public T getObj(){
return obj;
}
public void setObj(T obj){
this.obj = obj;
}
}
public class ObjectToolDemo{
public static void main(String [] agrs)
{
ObjectTool<String> ot = new ObjectTool<String>();
ot.setobj(new String("haha");
string h = ot.getObj();
System.out.println(h);
}
}
Object obj = new Integer(30);
相当于父引用指向子对象就是多态
public class ObjectTool{
private object obj;
public Object getobj()
{
return obj;
}
public void setObj(Object obj)
{
this.obj = obj;
}
}
public class ObjectsToolDemo{
public static void main (String [] agrs){
ObjectTool ot = new ObjectTool();
//使用1
ot.setObj(new Integer(2));
Integer i = (Integer) ot.getObj();
System.out.println(i);
ot.setObj(new String("haha"));
String s = (String) ot.getObj();
System.out.println(s);
//classcastException
ot.setObj(new Integer(11));
String q = (String) ot.getObj();
System.out.println(q);
}
}
向上转型没有问题,但是向下转型的时候其实隐含啦类型转换问题
也就是说这样的程序并不是安全的,所以在JDK5之后引入啦泛型,提高安全性
public class ObjectTool<T>{
private T obj;
public T getObj(){
return obj;
}
public void setObj(T obj){
this.obj = obj;
}
}
public class ObjectToolDemo{
public static void main(String [] agrs)
{
ObjectTool<String> ot = new ObjectTool<String>();
ot.setobj(new String("haha");
string h = ot.getObj();
System.out.println(h);
}
}