• Post Reply Bookmark Topic Watch Topic
  • New Topic

Type casting to a sub class  RSS feed

 
Vivian Josh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am curious about why does Java compiler allow type casting of an object of a super class into an instance of a subclass.

E.g. the following code compiles fine but fails at runtime.



I understand that the compiler wants to give benefit of doubt to sc under the assumption that the code that lead upto line 2 may have created bc to be really of type SubClass and not a BaseClass.
But isn't this a dangerous assumption to be made. Shouldn't it be more preferable to throw a compiler error than to await a confrontation with Runtime ClassCastException?
[ July 24, 2007: Message edited by: Vivian Josh ]
 
subodh gupta
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

Ok think about this i have created the method returning an object, you dont know the type of it but you know i have created a class named(say Hello) in which their's a function you need(say display) how you'll without thinking using the try-catch???
Ya one thing more you cant create its objects.

think abt the above problem and while working on java you face thousand of these problems.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It wouldn't be worth to make the effort for the compiler to detect this particular case, because it can't detect this kind of problem in general. Usually, there would be lots of other instructions between #1 and #2, and other threads might be accessing them as well, making it very hard if not impossible to prove that the cast will fail.

On the other hand, this problem manifests itself very quickly at runtime, and is then usually easily fixed, so I wouldn't consider this to be problem.
 
Vivian Josh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ulf and Subodh for your replies.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!