• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting - Inheritence  RSS feed

 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • 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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!