This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Casting problem" Watch "Casting problem" New topic
Author

Casting problem

Siddharth Bhargava
Ranch Hand

Joined: Feb 23, 2007
Posts: 257
Hi All,
I am unable to understand a very simple casting conversion of classes. Please help me clear my concept.!!!
Here is the code.

Employee.java
-------------


Manager.java
------------


ManagerTest.java
----------------


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

Thanks in advance.
Juva Yuva
Greenhorn

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
Marshal

Joined: Jan 10, 2002
Posts: 60741
    
  65

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


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

Joined: Feb 23, 2007
Posts: 257
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
*snip*

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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting problem
 
Similar Threads
please check this code
Derived Class & Method Calling
Is it me or just Eclipse... JEdit too...
Scanner class question
Polymorphism example