• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting Problem

 
garima jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...



then...



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.

Henry


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.
 
Henry Zhi Lin
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


Still have no clue why line 10 does not compile? The final class here is B not A.
[ November 21, 2008: Message edited by: Henry Zhi Lin ]
 
Devaka Cooray
ExamLab Creator
Marshal
Pie
Posts: 4252
227
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Henry Zhi Lin:

Still have no clue why line 10 does not compile? The final class here is B not A.


Line-10 is...
D d=(A)c;
How can you cast from C to A, while there are NO any is-a relationship between A and C? That is the reason.
[ November 21, 2008: Message edited by: Devaka Cooray ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic