gpt4 book ai didi

具有父类(super class)引用的 java 转换

转载 作者:搜寻专家 更新时间:2023-10-31 20:15:12 25 4
gpt4 key购买 nike

谁能解释一下这里发生了什么?

假设 CarBikeVehicle 的子类。

在我看来,Vehicle v 引用被强制转换为 Bike。我知道这是非法的,实际上编译器会吐出 ... Car cannot be cast to Bike

但这不应该是 Vehicle 不能转换为 Bike 吗?毕竟,Vehicle v 是一个Vehicle 引用。

public class Test {
public static void main(String[] args) {
Vehicle v = new Car();
Bike b = (Bike) v;
// some stuff
}
}

最佳答案

错误消息显示 Car 因为这是运行时异常。由于此时它知道 Vehicle 引用指向的实际实例(Car、Bike 或 Vehicle),因此它会给出更具体的错误消息。

如果这是编译时的一些异常,编译器会提到 Vehicle,因为编译器可能不知道 Vehicle 引用指向的实际实例。

关于具有父类(super class)引用的 java 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8221676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com