File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Casting problem" Watch "Casting problem" New topic

Casting problem

Siddharth Bhargava
Ranch Hand

Joined: Feb 23, 2007
Posts: 268
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.
Juva Yuva

Joined: Dec 18, 2008
Posts: 17
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 ]
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63865

"Juva Yuva", please check your private messages for an important administrative matter.

[Asking smart questions] [About Bear] [Books by Bear]
Siddharth Bhargava
Ranch Hand

Joined: Feb 23, 2007
Posts: 268
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 ....
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458

Sigh. Answer removed due to crosspost:
Please read this:
[ December 27, 2008: Message edited by: Bauke Scholtz ]
I agree. Here's the link:
subject: Casting problem
It's not a secret anymore!