• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Casting ......confusion

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Why does this code....compiles and runs fine.
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
b =s;
s=(Sub)b;
}}
But, at the same time this code produces Runtime ....ClassCastexception
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
s=(Sub)b;
b =s;
}}
can someone please explain.
Thanks,
Mukti
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In your 1st code b points to a class Sub object. In your 2nd code b does not points to a class Sub object. Down casting is not allowed.
 
Destroy anything that stands in your way. Except this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic