Why is there a ClassCastException, but not a compilation error?

Why don't I get a compilation error in the code below? I get a ClassCastException which is a bit confusing. Is it because they are connected?

 class Ink {} Interface Printable {} class ColorInk extends Ink implements Printable {} class BlackInk extends Ink {} class TwistInTaleCasting { public static void main(String args[]) { Printable printable = null; BlackInk blackInk = new BlackInk(); printable = (Printable)blackInk; } } 
+5
source share
3 answers

Why can't I get a compilation error in the code below?

Because the compiler only cares about the static type of expression that you are trying to execute.

Take a look at these two lines:

 BlackInk blackInk = new BlackInk(); printable = (Printable)blackInk; 

You know that in the second line, the value blackInk refers only to an object of type blackInk because of the first line, but the compiler does not. For the entire compiler (when compiling the second line), this could be:

 BlackInk blackInk = new PrintableBlackInk(); printable = (Printable)blackInk; 

... where PrintableBlackInk is a class that extends blackInk and implements Printable . Therefore, it is valid (at compile time) for translation from an expression of type blackInk to Printable . If you create a class blackInk a final , then the compiler knows that it will not work (if the value is not null) and will not be executed at compile time, for example:

 error: inconvertible types printable = (Printable)blackInk; ^ required: Printable found: BlackInk 

Details for this are in JLS 5.5.1 .

Otherwise, we need to wait for the runtime to see the failure, since the cast is performed at compile time.

+10
source

A ClassCastException is a run-time exception, so you can compile your code, but you will get a ClassCastException at runtime. You can also check javadocs - ClassCastException extends RuntimeException: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassCastException.html

The reason you get a ClassCastException is obvious because you are trying to classify the BlackInk instance as Printable (when you throw an object into a subclass that is not an instance, you will get a ClassCastException at runtime). In short, when you are casting, you are using type conversion, and it must be a valid operation, otherwise you will get ClassCastExecption at runtime.

+3
source

The setup will be completed correctly. However, at runtime, since TwistInTaleCasting and Printable not related, a cast class exception is thrown. Since ClassCastException is ** notchecked exception **, it is normal not to handle any such case in your code.

+1
source

Source: https://habr.com/ru/post/1200411/


All Articles