• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Casting of Objects

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey everybody,
Here is a code :

1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
The answer given is a - I thought Sub s = (Sub) b; is a valis narrowing cast.
What do you say ?
Pallavi
Edited by Corey McGlone: Broke up long line in code section to preserve page formatting.
[ April 04, 2003: Message edited by: Corey McGlone ]
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code gives a ClassCastException at runtime. You can not cast a parent class into a child class.
 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i can add that if you change the code of constructing object as follows:
Base b=new Sub();
it'll compile and run successifully
 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pallavi,
I think the given answer is wrong. It compiles fine and then throw a run time error -ClassCastException.
You are right, the answer should be C or 3 : Runtime Exception
 
Now I am super curious what sports would be like if we allowed drugs and tiny ads.
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic