Dear All , I faced the attached question in Exam Lab, and I still cant figure it out why there are two illegal casts , the reference variable is of the same type we are casting the object to , so it should compile ... please explain
I think above is Illegal because r1 is just an Interface reference type,not of type array.
ra1 = (Runnable) ca; //Illegal
In this case also same situation holds good. If you want to make this work change ca to array type and make C a non final class. OR typecast ca to just Runnable reference by making C a non-final class.
Hatem, you just need to understand that you cannot type cast between a single element type and an array type, like
This is applicable for both primitive and objects. The only exception is Object type. Since it is the super type of all the types, you can assign an array to it. So any cast between a reference type will not work.
Now a cast between two non-related classes is not allowed. So if you try
Here String and Integer classes are in different hierarchy so the cast is not allowed. But a cast is allowed between an interface type and another interface type or class.
The basic idea behind this is that at runtime, the cast might be successful as there might be a type, which is sub-type of both the interfaces or one interface or class. The cast between C1 and C2 is not allowed because under no circumstances, can there be an object which is compatible with both (as a class cannot extend multiple classes). Suppose I create a class like this
Now if we review the original type casts, then they will all work
But the cast is not allowed between a non-related class and interface, if the class is final
In this case there cannot be a class, which is a sub-class of both I1 and C1 (as C1 is final). This is why the cast will generate a compilation error.