Forums Register Login
Casting problem
Hi All,
I am unable to understand a very simple casting conversion of classes. Please help me clear my concept.!!!
Here is the code.




Please help me in understanding this code. This code is shaking my concept of Object conversion type casting.

Thanks in advance.
Originally posted by Siddharth Bhargava:

During Compile time, compiler believes the code and casting that was done. But during runtime , it actually checks the type of the object while casting.

the first line(Manager manager = (Manager)staff[0]; ) works , because staff[0] is actually an object of Manager .

the second assignment will fail , because the staff[1] contains Employee object which cannot be cast to it subclass (Manager)

Always remember the rule , that Manager is a Employee , but all employees cannot be Manager. Try working out is-a relationship and cast it.
So ,
[ December 27, 2008: Message edited by: Juva Yuva ]
"Juva Yuva", please check your private messages for an important administrative matter.
But we do cast superclass objects to subclass references. Like for example in the following code.

This example works wherein we are :
1) typecasting superclass reference (o) to the subclass object (A1)
Object o = new A1();
A1 abc = (A1)o;

2) The same thing we are typecasting the superclass reference (a1) to the subclass object (B1) and its methods are being called ab.method() and ab.bmethod()

Its very confusing please help me ....

Sigh. Answer removed due to crosspost: http://forums.sun.com/thread.jspa?threadID=5357652
Please read this: http://faq.javaranch.com/java/BeForthrightWhenCrossPostingToOtherSites
[ December 27, 2008: Message edited by: Bauke Scholtz ]
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards

All times above are in ranch (not your local) time.
The current ranch time is
Oct 22, 2017 06:40:19.