You get the runtime exception because Base never implements the Observer interface. This won't complain at compile time as we are allowed to cast objects to any Interface type, this allows subclass of base to implement other interface(s) (if need)
However you can use the instanceof operator to check the runtime type of the object before you apply any cast.
You can cast any object to an interface type, even if this class does not implement that interface. Because a subtype of this class could implement it (example with something). "You can cast" in this context means, the compiler allows it, but you get a class cast exception.
There is one exception, when the class is final, compiler complains:
But something that works:
prints "iii in Achild" Therefore the casting to all interfaces must be allowed from the compiler for all non-final classes.
Thanks for the explanation. So final classes can't be cast to a reference type of an interface. Am I right?? Or is it that final classes can't be cast to any other type?? Is that right?? Please confirm.
Originally posted by Jothi Shankar Kumar Sankararaj: Bu,
Thanks for the explanation. So final classes can't be cast to a reference type. Am I right??
Basically, what Bu said was... if a class is final, and doesn't support a particular interface, then the compiler can tell that a cast to that interface is not valid and complain. If the class is not final, then the compiler can't tell if a subclass of that class can implement that interface and hence, it will not complain.
This doesn't mean that the cast is valid. It just means that it can't tell you of the validity during compile time -- if the cast is not valid, it will complain at runtime.
Henry [ December 19, 2006: Message edited by: Henry Wong ]
Interface references can be casted and assigned to class references with the assumption that any of the subclass object inheriting the our interface in the same hierarchy might be stored in the interface reference.
But the final classes can't be further inherited. So Until unless the interface is implemented anywhere in the hierarchy till our final class they can't casted to the final class reference.