Java casting resulting in run-time error instead of compilation error

前端 未结 7 904
感动是毒
感动是毒 2020-12-03 19:51

The following code snippet will result in a run-time:

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

class Ca         


        
7条回答
  •  情深已故
    2020-12-03 20:35

    In theory, it would be possible for a compiler to say to itself: "v is local variable, that is assigned to be a Car. At no point prior to the attempted cast to Bike does it change its value, and there is no way for Car to be successfully cast to Bike. Therefore, this is an error."

    However, I know of no Java compiler that will do that analysis for you. It's really only worthwhile in the simplest of cases. Instead, the behavior is that the compiler sees the cast, and reasons that it is possible to cast a Vehicle to a Bike, and so it allows it.

    In general, that's what a cast means: it tells the compiler that even though this assignment might fail, you're pretty certain that it won't. In exchange for allowing the code to compile, you assume the risk of a run-time exception.

提交回复
热议问题