Even though "Unrelated" interface is no where in the hierarchy, still the code compiles fine. It will ofcourse error with ClassCastException at run time; But why does it compile? Where is the static type check the way it gets done for classes?
The compiler can't be sure what kind of object is referenced by the variable ac when you perform the cast to (Unrelated). For all the compiler knows, ac might be a reference to an object that is a subclass of AnyClass and that also implements Unrelated, in which case there would be no ClassCastException. Consider this example:
That code compiles and runs without any errors. Again, the compiler doesn't know at compile time what type of object ac is a reference to. It only knows that ac is an AnyClass reference which might be referencing an instance of some subclass of AnyClass, such as the class I called Sub. Because a subclass can implement the Unrelated interface even if the super class does not, the compiler assumes that you know what you're doing and that ac must be a reference to some object that implements Unrelated.
SCJA 1.0 (98%), SCJP 1.4 (98%)
Joined: Jul 20, 2005
Thanks Joseph. That was my initial guess (after being pointed out by Marcus Green). But should not the compiler see that theres no such class hierarchy exists that can make it possible?
Well the outcome is: You can cast any class to any interface!
Thanks Ernest for point that out! Thanks all for taking time to reply to my query.
Joined: Apr 10, 2005
Originally posted by Prasanta Chinara: But should not the compiler see that theres no such class hierarchy exists that can make it possible?
No, the compiler cannot and should not make any assumptions about the existence of a class hierarchy. There are many classes that are not part of the standard Java libraries, including the classes you make yourself. If the compiler assumed that the only classes in existence were the ones in the standard library, then you and I would not be able to compile or use any new classes.