Source:http://www.examlab.tk/ Practice Exam:3 Question# 48
In the above program, line 10 gives compile time error. And line no 9 throws CastcastException at run time. Both the errors/exceptions are related to casting. How do we decide whether the issue related to casting will be visible at compile time or run time. Does it have to do something with interface. Please explain.
I'm going to just copy/paste this reply by Henry again as it is essentially the same problem.
Originally posted by Henry Wong: Here is a concrete example. Supposed that you have this...
This is allowed -- even though C does not implement the interface I. The compiler only knows it as the class type B, and it is theortically possible for a new class, say D, to subclass B, and implement I.
This is *not* allowed. The compiler knows it as the class type C, and since class type C is a final class, it is not possible for a new class, say E, to subclass C, and implement I.
This answer was dealing with the final modifier but it gives a good explanation of what the compiler is looking at. In your example though A does not implement I so it throws a CastcastException at run time. At line 10 there is no way you could subclass D and also subclass A so the compiler complains because it knows at compile time that it's impossible. Hope that made any since.