考虑两个简单的类
public class Parent
{
public void ShowData()
{
}
}
public class Child : Parent
{
public void GetData()
{
}
}
// Upcasting -- NO ERROR
Parent objParent = new Child();
// Downcasting -- ERROR
Child objChild = new Parent();
// Downcasting -- NO ERROR
Child objNewChild = (Child)new Parent();UpCasting不需要explicit casting?DownCasting需要explicit casting?发布于 2015-06-02 12:47:02
因为Child是Parent,但是Parent不一定是Child。因此,只有当实际实例是Parent或Child的子类时,才能将Child转换为Child。不能保证Parent的某些实例或Parent的子类是Child。在这种情况下,您已经展示了new Parent()构造了超类的一个实例。它将编译,但您将得到一个运行时异常。
https://stackoverflow.com/questions/30596441
复制相似问题