Inheritance 类型转换时的ClassCastException

Inheritance 类型转换时的ClassCastException,inheritance,parent-child,classcastexception,Inheritance,Parent Child,Classcastexception,我知道这似乎很简单,但我想知道这背后的深层原因 我有下面的代码,其中有一个ClassCastException Parent parent = newParent(); Child child = (Child)parent; //ClassCastException: Parent cannot be cast to Child. 我已经用下面的代码修改了相同的代码并成功地执行了 Parent parent = new Pa

我知道这似乎很简单,但我想知道这背后的深层原因

我有下面的代码,其中有一个ClassCastException

Parent parent = newParent();
Child child = (Child)parent;   //ClassCastException: 
                               Parent cannot be cast to Child.
我已经用下面的代码修改了相同的代码并成功地执行了

Parent parent = new Parent();
Child child = new Child();
parent = child;
System.out.println(parent.color); 
child=(Child)parent; 
System.out.println(child.color);

**output:** 
       Parent_color
       Child_color

我只是想知道是什么造成了区别结果的主要差异?如果在运行时有成功的可能性,Java中允许向下转换

子女=(子女)父母

编译器将允许这样做,因为在运行时“parent”可能引用“Child”的实例。但它在运行时失败,因为“parent”不是指“Child”的实例,而是指“parent”的实例

让我们看看如果没有ClassCastException会发生什么:

假设您已按如下方式定义了类:

class Parent {

void aMethod(){
}

}

class Child {

void bMethod(){
}

}
假设我们定义了这些语句

1. Parent parent = new Parent();
2. Child child = (Child)parent;
3. child.bMethod();// we should be able to do this, because there should not be any issue executing methods defined in "Child" type with a reference variable of "Child" type.
但是最后一行是非法的,因为我们的父类中不存在名为“bMethod”的方法,我们正在尝试执行一个甚至不存在的方法。希望这能证明“ClassCastException”的合理性

现在,让我们检查一下您修改过的代码:

   1. Parent parent = new Parent();
   2  Child child = new Child();
   3. parent = child;
   4. System.out.println(parent.color); 
   5. child=(Child)parent; 
   6. System.out.println(child.color);
这是演员阵容

child=(Child)parent; // works as you expected, parent is now referring to an instance of "Child" according to the assignment "parent = child" at line no 3.

工作正常,因为“parent”现在指的是“Child”类的实例。因此,“child”引用变量现在只引用“child”的实例,运行时环境对此很满意。

如果在运行时成功,Java中允许向下转换

子女=(子女)父母

编译器将允许这样做,因为在运行时“parent”可能引用“Child”的实例。但它在运行时失败,因为“parent”不是指“Child”的实例,而是指“parent”的实例

让我们看看如果没有ClassCastException会发生什么:

假设您已按如下方式定义了类:

class Parent {

void aMethod(){
}

}

class Child {

void bMethod(){
}

}
假设我们定义了这些语句

1. Parent parent = new Parent();
2. Child child = (Child)parent;
3. child.bMethod();// we should be able to do this, because there should not be any issue executing methods defined in "Child" type with a reference variable of "Child" type.
但是最后一行是非法的,因为我们的父类中不存在名为“bMethod”的方法,我们正在尝试执行一个甚至不存在的方法。希望这能证明“ClassCastException”的合理性

现在,让我们检查一下您修改过的代码:

   1. Parent parent = new Parent();
   2  Child child = new Child();
   3. parent = child;
   4. System.out.println(parent.color); 
   5. child=(Child)parent; 
   6. System.out.println(child.color);
这是演员阵容

child=(Child)parent; // works as you expected, parent is now referring to an instance of "Child" according to the assignment "parent = child" at line no 3.
工作正常,因为“parent”现在指的是“Child”类的实例。因此,“child”引用变量现在只引用“child”的实例,运行时环境对此很满意