Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

Casting between interfaces and classes

Hi


In the question, there is no relation between interface I and class A and in the line 9, they are trying to cast to I which would give compile time error. Let me know how this line 9 will be able to compile

The rule of thumb is you can cast (at compile time) between any non-final class and interface even if they have no is-a relationship.


The reason behind this is explained very well with examples in our "object orientation tricks" document:

http://www.examlab.org/lesson/tricks-of-java-object-oriented-programming.pdf


In a nutshell, this happens because there could be another separate class (let's say Intermed) which extends the class in the question, and implements the interface in the question at the same time. When that happens, you should be able to create an object of Intermed with a reference of the class in the question. When you do that, you should be able to cast that reference to the interface in the question, which should be valid at both compile and run time because the actual object that reference contains is an object of Intermed, which shares an is-a relationship with the interface in the question. For that to be possible, we need to be able to cast between any interface and class at the compile time.


Question for you: what would happen when the class is marked as final?

ExamLab © 2008 - 2024