有谁知道原因:
public void foo()
{
System.out.println("Hello");
return;
System.out.println("World!");
}
Run Code Online (Sandbox Code Playgroud)
将被报告为Eclipse下的"无法访问的错误",但是
public void foo()
{
System.out.println("Hello");
if(true) return;
System.out.println("World!");
}
Run Code Online (Sandbox Code Playgroud)
只触发"死代码"警告?
我能想到的唯一解释是Java编译器只标记第一个,而Eclipse中的一些额外分析计算出第二个.但是,如果是这种情况,为什么Java编译器不能在编译时弄清楚这种情况呢?
Java编译器不会在编译时弄清楚if(true)没有效果,从而产生基本相同的字节码吗?在什么时候应用可达代码分析?
我想一个更通用的方法来思考这个问题是:"什么时候应用可达代码分析"?在将第二个Java代码片段转换为最终字节码时,我确信在某些时候删除了"if(true)"运行时等效项,并且两个程序的表示变得相同.然后,Java编译器不会再次应用其可访问的代码分析吗?
以下代码段将导致运行时:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么会导致运行时错误而不是编译错误?难道编译器不应该知道'v'已经是'Car'并且不能被投入'Bike'吗?
想象一下,一个类别的Cottage扩建了建筑和代码
Building building = new Building();
Cottage cottage = (Cottage)building;
Run Code Online (Sandbox Code Playgroud)
现在,考虑到java继承的本质,完全有意义的是不能将Building转换为Cottage,但对我来说没有意义的是这个编译.为什么要编译然后抛出运行时ClassCastException?
在实际运行程序之前,构建是否是对Building对象的引用是不是很明显?
作为一个普遍的问题,我知道我得到了一个可能重复的这个:)但我找不到答案为什么它的编译问题:)
EDIT2我在这里接受了一个很好的答案(更不用说下面的讨论了:)),但我仍然在Java中找到了接受的答案,导致运行时错误而不是编译错误最有趣......
编辑我编辑了IllegalCastException并输入了正确的ClassCastException