假设:
class A {
public int fieldA = 0;
}
class B extends A {
public int fieldB = 0;
}
现在,我想从 A 创建一个 B 的实例:
A a = new A();
B b = (B) new A();
这给出了一个 classCastException。我可以在 B 中创建一个采用 A 实例并复制字段的构造函数,但这显然不实用:
class B extends A {
public int fieldB = 0;
B (A a){
fieldA = a.fieldA;
}
}
谢谢你的帮助
最佳答案
举个例子
public class Animal
{
public void eat(){}
}
public class Dog extends Animal
{
public void eat(){}
public void main(String[] args)
{
Animal animal=new Animal();
Dog dog=(Dog) animal; //will not work
}
}
通过使用强制转换,你实际上是在告诉编译器“相信我。我是专业人士,我知道我在做什么,我知道虽然你不能保证,但我告诉你这动物变量肯定是狗。”
因为动物实际上不是狗(它是动物,你可以执行 Animal animal = new Dog(); 它会是狗)虚拟机在运行时抛出异常,因为你违反了信任(你告诉编译器一切都会好的,但事实并非如此!)
编译器比盲目接受一切更聪明,如果你尝试在不同的继承层次结构中转换对象(例如将 Dog 转换为 String),那么编译器会把它扔回给你,因为它知道永远不会可能工作。
因为您本质上只是阻止编译器提示,所以每次您强制转换时,重要的是检查您不会通过在 if 语句(或类似的东西)中使用 instanceof 来导致 ClassCastException。
在你的情况下,你是说我的引用 b 将指向点 B 的对象,然后你让它指向类 A 的对象(这不是引用 b 期望的类 B 的对象)。因此你得到了 classCastException。
你可以这样做
A a = new B();
B b = (B) a;
关于java - 从父类(super class)创建子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16832612/