Java中的向下转换抛出ClassCastException

时间:2018-10-09 06:41:32

标签: java casting downcast

我不明白为什么波纹管的浇铸不起作用(Helicopter h = (Helicopter) new Rotorcraft();)和throwsRuntime exception类型的ClassCastException

基类:

public  class Rotorcraft {

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

儿童班:

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();
    }
}

1 个答案:

答案 0 :(得分:2)

一个基本的问题是,您正在尝试将不是Helicopter的内容转换为Rotorcraft。强制转换不能更改对象的运行时类。

您的意思是简单地写:

Helicopter h = new Helicopter();