Hie Yojana,
I will only try to discuss casting with reference types.So, when you are casting reference types in
Java, the only requirement for a successful compilation is that the old type and the new type you are casting to should be related by inheritence.Here it does not matter which is the superclass and which is the sub class.So what does this mean ?
Assume the following declarations :
--------------------------------------------------------------
class Base{}
class Sub1 extends Base{}
class sub2 extends Base{}
---------------------------------------------------------------
From this, we can draw the following hierachies
A. Base->Sub1
B. Base->Sub2
So it means we can safely write :
-----------------------------------------------------------------
1. Base base = (Base)new Sub1()
2. Sub1 sub1 = (Sub1)new Base()
3. Base base = (Base)new Sub2()
4. Sub2 sub2 =(Sub2)new Base()
However YOU CAN NOT write :
a. Sub1 sub1 =(Sub1)new Sub2()//WRONG!!!
b. Sub2 sub2 = (Sub2) new Sub1()//WRONG
because Sub1 and Sub2 are not related by inheritence, that is, in the hierachies we drew above there is not path between sub1 and sub2.
Now after compiling a cast safely, all is not done and well until run time.At runtime, your cast will succeed IFF the true class of the object stored in the old type is actually the new type or its sub class.The true class of an object is the one you use when you call new.That is refering to the objects created above we have
A) 1. creates an object of type Sub1.This will succeed at runtime because we are casting it to Base and Sub1 is a subclass of base.
B) 2. will fail at runtime because we are creating an object of type base and casting it to Sub1 which is not the superclass of base.
C) 3. will succeed with the same rationale as in A above.
D) 4. will fail with the same reason as in B above.
E)The following will also work:
Base base = new Sub1();
Sub1 sub1 =(Sub1)base
because inside base we have stored an object whose true type is actually Sub1, although the variable itself is of type base.
I hope this gives a bit of more ground.Some people might hava to verify if along the way I did not get lost with types.
Regards,
Herbert.