wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Does the compiler check the validity of casts involving interfaces?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Does the compiler check the validity of casts involving interfaces??" Watch "Does the compiler check the validity of casts involving interfaces??" New topic
Author

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

Sirish Kumar
Greenhorn

Joined: Jan 28, 2004
Posts: 15
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
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
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).


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. <br />- What truth? <br />- That there is no spoon!!!
 
Don't get me started about those stupid light bulbs.
 
subject: Does the compiler check the validity of casts involving interfaces??
 
Similar Threads
inheritance question
No array bounds checking when init with null?
Regarding Casting between classes and interface
name conflict
Following code shows ClassCastException