• 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

Casting - Inheritence

 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am very much confused with logic behind typecasting of super class object to subclass and vice versa which is allowed and which is not allowed.
after type casting if the overridden method is invoked which one will be invoked and WHY.can someone hel me by explaining or give some articles to go through
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just remember that casts can't change anything; they only tell the compiler what it doesn't know will be happening at runtime. So if you've got an object whose class is Child, and Child is a subclass of Parent, the following are all legal;

Child c = new Child();
Parent p = new Child();
Child c2 = (Child) p;
Parent p2 = (Parent) c; // Cast is legal, but not needed

Given that Parent has another subclass named Kid, then the following are all illegal:

Kid k = new Kid();
Parent p = new Parent();
Child c = new Child();

Child c2 = (Child) k; // Won't compile because a Kid is never a Child
Child c3 = (Child) p; // Will fail at runtime, because p points to a Parent not a Child
Kid k2 = (Kid) c;
Kid k3 = (Kid) p;

So the legal casts are the ones that tell the truth about the real classes of the objects; the illegal ones are the ones that lie.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic