• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Type casting to a sub class

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Ulf and Subodh for your replies.
 
reply
    Bookmark Topic Watch Topic
  • New Topic