File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Interface cast Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Interface cast" Watch "Interface cast" New topic

Interface cast

Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
How is it that the following code doesn't result in a compile-time error considering that class Jchq doesn't implement interface Bicycle?

interface Bicycle{
public void Bicycle();
public class Jchq {
public static void main(String argv[]){
Jchq j = new Jchq();
Bicycle b = (Bicycle) j;
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Very good case!

From the Java Language Specifications, 2nd Edition:

The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows:
If S is a class type:

* If T is a class type, then S and T must be related classes-that is, S and T must be the same class, or S a subclass of T, or T a subclass of S; otherwise a compile-time error occurs.
* If T is an interface type:
o If S is not a final class (�8.1.1), then the cast is always correct at compile time (because even if S does not implement T, a subclass of S might).
o If S is a final class (�8.1.1), then S must implement T, or a compile-time error occurs.

I bolded the key sentence, which says that the object referenced by j could actually be a subclass of Jchq which does implement Bicycle. If this is not true, a run-time exception will be thrown.

This rule seems quite a stretch, considering the rule requiring compile-time provable initialization of variables before use, but there it is.

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link:
subject: Interface cast
It's not a secret anymore!