在下面的示例中:class Parent{ void fun() { System.out.println("Parent class"); }}class Child extends Parent{}public class Main { public static void main(String[] ar) { Child ch = new Child(); ch.fun(); }}继承示例,在实例化对象时,我们可以创建一个Parent ch = new Child();有效的对象,但是为什么不能有这样的对象呢Child ch = new Parent(); ?
2 回答
富国沪深
TA贡献1790条经验 获得超9个赞
在您的示例中,您有class Child extends Parent{。这意味着aChild是aParent但Parent不是a Child。Parent是更通用的父类(讽刺的),并且Child是更具体的子类。因此,您可以执行以下操作:
Parent ch = new Child();
因为您要声明通用Parent对象,然后将其实例化为Child对象。但是,您不能执行以下操作:
Child ch = new Parent();
因为您不能将其声明为更具体的Child对象,然后将其实例化为不太具体的Parent对象
炎炎设计
TA贡献1808条经验 获得超4个赞
Child ch = new Parent()之所以无效是因为并非每个人Parent都是一个Child。假设您有第三堂课:
class AnotherChild extends Parent {int age = 2;}以下内容也将有效:
Parent otherChild = new AnotherChild();
如果Cild child = new Parent()要使之有效,则出于相同的原因
Child child = new AnotherChild()
会也必须作出有效的,因为AnotherChild 是一个 Parent。
现在很明显,这是有问题的,因为Child与有所不同AnotherChild。
选择该示例是为了使其显而易见,但即使是简单的Parent对象(new Parent())也不是Child实例,因为它没有使用Child该类或其任何子类实例化。
所有这些都是编译时类型检查,可确保代码安全性和对象/变量兼容性。可以使用允许的强制转换解决该问题,但是如果运行时对象实际上是不兼容的类型,则执行仍然会失败。
添加回答
举报
0/150
提交
取消
