gpt4 book ai didi

Java 转换导致运行时错误而不是编译错误

转载 作者:搜寻专家 更新时间:2023-11-01 01:04:10 25 4
gpt4 key购买 nike

以下代码片段将导致运行时:

class Vehicle {
public void printSound() {
System.out.print("vehicle");
}
}

class Car extends Vehicle {
public void printSound() {
System.out.print("car");
}
}

class Bike extends Vehicle {
public void printSound() {
System.out.print("bike");
}
}

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

v.printSound();
b.printSound();
}
}

我的问题是:为什么会导致运行时错误而不是编译错误?编译器难道不应该知道 'v' 已经是 'Car' 并且不能转换为 'Bike' 吗?

最佳答案

从理论上讲,编译器有可能对自己说:“v 是局部变量,它被分配为 Car。在任何时候之前尝试转换为 Bike 是否会更改其值,并且 Car 无法成功转换为 Bike。因此,这是一个错误。”

但是,据我所知,没有任何 Java 编译器可以为您进行这种分析。只有在最简单的情况下才真正值得。相反,行为是编译器看到了转换,并且可以将 Vehicle 转换为 Bike,因此它允许这样做。

一般来说,这就是强制转换的意思:它告诉编译器即使这个赋值可能会失败,你也很确定它不会。作为允许代码编译的交换,您承担了运行时异常的风险。

关于Java 转换导致运行时错误而不是编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388136/

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