Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

java - Why 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 little confusing. Is it because they are related?

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;
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Because the compiler only cares about the static type of the expression you're trying to cast.

Look at these two lines:

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

You know that in the second line, the value blackInk only refers to an object of type BlackInk due to the first line, but the compiler doesn't. For all the compiler knows (when compiling the second line) it could actually have been:

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

... where PrintableBlackInk is a class extending BlackInk and implementing Printable. Therefore it's valid (at compile-time) to cast from an expression of type BlackInk to Printable. If you make BlackInk a final class, then the compiler knows that there's no way that it will work (unless the value is null) and will fail at compile-time, like this:

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

The details for this are in JLS 5.5.1.

Otherwise, we have to wait until execution time to see the failure, because the cast is valid at compile-time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...