Two Laptop Bag*
The moose likes Beginning Java 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 » Beginning Java
Bookmark "Casting problem" Watch "Casting problem" New topic
Author

Casting problem

geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78
[edit]Corrected code tags. CR[/edit]
[ September 12, 2008: Message edited by: Campbell Ritchie ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39079
    
  23
Please use the buttons for tags, much quicker than writing them by hand, and more effective.

In the first case you are declaring your object as an Ab; there is no z field in Ab. When you have a new declaration as a Bc, then it is a class which does have a z field.

When you declare a variable of a particular type, the compiler can only find the members of the declared type. At runtime the versions of the actual type are used, which is polymorphism and works for overridden members (ie instance methods) only. A classcast like that is dangerous; if you get it wrong you can have your application stop with Exceptions.
arulk pillai
Author
Ranch Hand

Joined: May 31, 2007
Posts: 3220
try this:



Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 347
I think this has to with operator precedence..

You are trying to access member z of type a and then cast that to type Bc with this piece of code.. (if this worked you would have cast an int to a class )
System.out.println((Bc) a.z);

With this piece of code you are casting an object type a to type Bc and then accessing the member z of type Bc
System.out.println(((Bc) a).z);
[ September 12, 2008: Message edited by: Gamini Sirisena ]
geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78
thanks guys!!!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Originally posted by Gamini Sirisena:
I think this has to with operator precedence..

Correct; . is at the top of the operator precedence list. So it will always evaluate . (and [] / ()) first, and only then will it cast. So it was trying to cast a.z to Bc.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39079
    
  23
I forgot about the precedence problem
 
GeeCON Prague 2014
 
subject: Casting problem