Java 中的向下转换抛出 ClassCastException

Downcasting in Java throws ClassCastException

我不明白为什么来自波纹管的转换不起作用(Helicopter h = (Helicopter) new Rotorcraft();)和 throws 类型为 ClassCastExceptionRuntime exception

基础class:

public  class Rotorcraft {

protected final int height = 5;
    protected int fly(){
        return height;
    }
}

Child class:

public class Helicopter extends Rotorcraft {    
    private int height = 10;

    public int fly() {
        return super.height;
    }

    public static final void main(String[] a){
        Helicopter h = (Helicopter) new Rotorcraft();
    }
}

基本问题是您正在尝试将不是 Helicopter 的东西(它是 Rotorcraft)转换成 Helicopter。强制转换无法更改对象的运行时 class。

你的意思是简单地写:

Helicopter h = new Helicopter();

?