我有一些课程
public class Container {
static Map<String , Fruits> mp = new HashMap<String, Fruits>();
public static Map<String, Fruits> getMp() {
return mp;
}
}
FruitsClass
public class Fruits {
private String color;
private String shape;
public String getColor() {
return color;
}
public String getShape() {
return shape;
}
}
扩展水果的Apple类
public class Apple extends Fruits {
private String color;
private String shape;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getShape() {
return shape;
}
public void setShape(String shape) {
this.shape = shape;
}
}
主类
public static void main(String[] args) {
Apple a = new Apple();
a.setColor("red");
a.setShape("round");
Container.getMp().put("fruits1",a);
System.out.println(Container.getMp().get("fruits1").getShape());
Apple b =(Apple) Container.getMp().get("fruits1");//does not throw runtime exception
Fruits f = new Fruits();
Apple as = (Apple) f;//throw runtime exception
}
我的问题是,在这两种情况下,我都在向Apple传播Fruit。但是当值来自hashmap时,它不会引发异常。我对此非常困惑。请有人能解释一下这背后的原因。
答案 0 :(得分:1)
Apple b = (Apple) Container.getMp().get("fruits1");
这不会抛出ClassCastException
,因为运行时的对象的类型是Apple
,您之前创建并放入地图中。
Fruits f = new Fruits();
Apple as = (Apple) f;
抛出ClassCastException
因为,在运行时,f
是Fruits
对象,而不是Apple
。
答案 1 :(得分:1)
当您从地图get
Apple
时,地图中放置的对象最初为Apple
。因此,将地图返回的Fruit
向下转换为Apple
的工作原理 - 在运行时,该对象确实是Apple
。
但是,f
是Fruits
,而不是Apple
,因此向下转换为Apple
会抛出ClassCastException
。对象f
不是Apple
,因此演员表失败。
它与对象是否来自地图无关;这一切都取决于对象的运行时类型。