Forums Register Login

Does the compiler check the validity of casts involving interfaces??

+Pie Number of slices to send: Send
Hi Ranchers,
Well I guess this has become a habit now. I cleared SCJP 1.4 last week. But I was still going through some articles on the net when this question popped up. Have a look at the following code.

As expected line 1 gives a compilation error since the class ShapeClass and Test are not related. Thus the cast fails the compile time check and hence the error.

However line 2 compiles without any errors. Now this was unexpected. I was under the impression that the compile time is also applicable to interfaces as well. So does this mean that the compiler does not perform the compile time check in case of interfaces?? If so , why is it so???

Looking for any inputs
Regards
Sirish Kumar
+Pie Number of slices to send: Send
You may want to read 'Casting Conversion' from the JLS.
Specialy the part where it says:
If T is a class type that is not final (�8.1.1), then the cast is always correct at compile time (because even if T does not implement S, a subclass of T might).
Yes, my master! Here is the tiny ad you asked for:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 442 times.
Similar Threads
name conflict
No array bounds checking when init with null?
Following code shows ClassCastException
inheritance question
Regarding Casting between classes and interface
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 15, 2024 23:10:30.