大家好,
想知道是否有任何 Java 黑客可以告诉我为什么以下方法不起作用:
public class Parent {
public Parent copy() {
Parent aCopy = new Parent();
...
return aCopy;
}
}
public class ChildN extends Parent {
...
}
public class Driver {
public static void main(String[] args) {
ChildN orig = new ChildN();
...
ChildN copy = orig.getClass().cast(orig.copy());
}
}
代码很高兴编译,但决定在运行时抛出 ClassCastException D=
编辑:哇,真的很快回复。多谢你们!所以看来我不能使用这种方法进行向下转换......还有其他方法可以在 Java 中进行向下转换吗?我确实考虑过让每个ChildN
类都覆盖copy()
,但并不热衷于添加额外的样板代码。