• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic