• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting problem

 
Siddharth Bhargava
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64993
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Juva Yuva", please check your private messages for an important administrative matter.
 
Siddharth Bhargava
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
*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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic