Tuesday 19 March 2013

Casting in Java - when error, when exception?

Leave a Comment
Parent p1 = new Child();     
        Parent p2 = new Parent();     
        Child c1 = (Child) p2;    
       Child c2 = (Parent) p1;   
The code above says,
1.
Create an object Child and assign it to a ref to Parent p1 -- Thats ok, all Child can be ref by Parent like All Dogs can be ref by Animal... Dog IS A Animal
2.
Create an object Parent and assign it to a ref of Parent p2 -- No doubt!.. that's prefect.
3.
Cast a Parent to Child and store it on Child, please note we are not creating any object here. Now compiler wont complain since you explicitly want an Animal to be a Dog, legal but not appropriate to cast without checking -- Runtime error in this case!!
4.
Cast a Parent ref (which holds a Child) to Parent and refer it using Child.... gotcha!.. Animal IS-A Dog?? that may not be true, and hence compiler complains.

Parent p = new Child();  
It's legal, but 'p' will only be able to do Parent things. The compiler says "all right... good to go"
Child c1 = (Child) p2;  
This will compile, because you're trying to tell the compiler "It's okay.... I know it's weird." The compiler believes you. But then the cast happens at runtime, there's an exception because the p2 object doesn't have all the "stuff" it needs to make it a Child object.

0 comments:

Post a Comment