faizaharis,
here I am listing the thumb rules for casting and conversion given by RHE.
For object Reference Conversion,
- An Interface may only be converted to its super interface or to Object
- A class type may be converted to its superclass type or its superinterface type.
- An Array may be converted to an Object type , a Cloneable interface type or an array of Superclass type
For Object Reference Casting
Let's say the casting is like this
- Compile time
- When both OldType and NewType are classes, one class must be a subclass of the other.
- When both OldType and NewType are arrays, it must be legal to cast an element of OldType to an element of NewType (Refer to the prev. rule).
- We can always cast between an interface and a non-final object.
- Run Time
- If the NewType is a class, the underlying object in ot must be of NewType or must have inherited from NewType
- If the NewType is an interface, the underlying object in ot, must implement NewType.
Based on these rules,
1. Runnable rn = obj;
will not compile since obj is a reference to Object and Object does not implement Runnable.
2. Runnable rn = (Runnable)obj;
will compile and run, since you can cast to any interface type, and the underlying object in obj implements Runnable.
3.Observer ob = (Observer)aone;
will have runtime error, since the class of aone, One does not implement Observer.
4.Observer ob2 = obj;
will have compile time error, since you cannot cast an Object reference to Observer, since Object does not implement Observer.
One more thing to be noted while casting is,
- Compile time rules apply to the references
- Runtime rules apply to the underlying objects.
Hope, I am right,
If there's anything wrong, please point it!!
Thanks and regards,
Suresh.
[This message has been edited by Suresh (edited May 21, 2000).]