Author | Topic: Casting |
Alk greenhorn |
posted February 17, 2000 01:16 PM
class Base {} class Sub extends Base {} class Sub2 extends Base {} public class CEx{ public static void main(String argv[]){ } this gives run time error, Sub is subclass of
|
maha anna bartender |
posted February 17, 2000 02:06 PM
Base b=new Base(); Sub s=(Sub) b; // As long as the type of LHS matches with type of RHS the compiler says ok. Here var b is superclass and it CAN BE CASTED as one of its subclasses. The compiler DID that check also and said Ok. But Only at run time real truth is known that the physical object held by b was actually superclass BASE not of SUB and it CAN NOT be seen as Sub. If the above line would have been changed either as Base b = new Sub(); //OR Base b = new Sub1(); Sub s = (Sub)b; (note that the casting is unnecessary here) no Runtime error will occur. Because the REAL OBJECT CREATED in heap was of type Sub/Sub1 which can be easily casted to one of its superclasses above in its inheritance hierarchy I hope it helps. regds Maha Anna [This message has been edited by maha anna (edited February 17, 2000).]
|
Rich Wardwell greenhorn |
posted February 17, 2000 02:15 PM
You can't cast the parent class to the base class in the situation per your code snippet. It will let you through the compile time checks since a Base class could/may hold an instance of it's subclass. Unfortunately, it's clear from your code that it is not hold an instance of it's subclass, but of the parent, therefore you receive the ClassCastException error. Explicit object casting can goes down the inheritance hierarchy, implicit casting goes up the inheritance hierarchy. Going up is not a problem. Going down, you better be sure that what you are explicitly casting can be held by the reference. The following would work: Base b = new Sub(); Sub s = new Sub(); BUT THIS WOULD NOT Base b = new Base();
|
gunjan ranch hand |
posted February 17, 2000 06:03 PM
To make it simple: Think of is a relationship. 1. Subclass "IS A" type of parent class. However Parent class IS NOT A subclass. Therefore you cannot cast two unequal classes 2. As far as I know references are evaulated at run time in assignments and primitives at compile time. So above code works at compile time. Regards
|
| | |