• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting problem

 
geet kaur
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[edit]Corrected code tags. CR[/edit]
[ September 12, 2008: Message edited by: Campbell Ritchie ]
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3388
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try this:

 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys!!!
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I forgot about the precedence problem
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic