我在这个结构中有两个实体:
class Parent{
public int type;
//Setters and getters
}
class Child1 extends Parent{
}
我有一个 Parent
实例,我想根据条件将其转换为 Child1
:
Parent parent = ...
if(parent.getType() == 1)
Child1 child = (Child1) parent;
但它给了我ClassCastException
。我该如何解决这个问题?在 java 中使用向下转型的最佳方法是什么?
最佳答案
您无法将父类型对象转换为子类型对象。您误解了继承行为。
关于java - 无法转换为子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431997/