Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Sirish Kumar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic