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

前端 未结 7 899
感动是毒
感动是毒 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:15

    Type casting of object occurs at run time so compiler doen't recognize it

    0 讨论(0)
  • 2020-12-03 20:28

    For

    R r = /* some code to initialize "r" */
    T t = (T) r;
    

    The Java Language Specification says:

    If R is an ordinary class (not an array class):

    • If T is a class type, then R must be either the same class as T or a subclass of T, or a run-time exception is thrown.
    • If T is an interface type, then R must implement interface T, or a run-time exception is thrown.
    • If T is an array type, then a run-time exception is thrown.
    0 讨论(0)
  • 2020-12-03 20:32

    Casting from super class may work, so it is allowed (during compilation). Casting from a totally different class is not allowed, for example:

    Integer a = 1;
    String b = (String)a; // compile error
    String b = (String)(Object)a; // runtime error
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 20:36

    The semantics of Java say that this must result in a run-time error. In this case it's possible to look at the code and see that it will definitely throw an error at runtime, but how does the compiler know that a ClassCastException isn't what you wanted?

    Editors like IntelliJ and Eclipse can (and do) notice these kinds of errors and warn you about them, but the rules of Java say that this is legit code that must compile.

    0 讨论(0)
  • 2020-12-03 20:39

    No. v is a Vehicle and it might be possible to cast it to Bike. It's not the compiler's job to figure out the actual runtime types of every object (especially because sometimes that's impossible).

    0 讨论(0)
提交回复
热议问题