Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting this

 
Vaibhav Shridish
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following are 2 examples from Rasmussen
where in this has been typecasted
y does first one give compilation error where as the second one doesnt?

public class myclass
{
public static void main(String args[])
{
.....
}
public static class class state
{
protected int value;
..........
class momento
{
int value=10;
momento() {this.val=state.this.val;}
void restore()
{
((state)this).val=this.val; //1
}
}
}
}
The above code gives a compilation error at 1
whereas the following doesnt at 2 and 3 WHY ?
class light
{
protected double getbill(int ..){}
protected String billtype;
.....
}
class tubelight extends light{}
class neonlight extends tubelight
{
.....
((light)this).getbill(20);//2
System.out.println((light)this).billtype);//3
}
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First it would be a good thing to cut and paste the code correctly instead of rewriting it and introducing a couple syntactic errors (val instead of value, class class instead of class,...)
Anyway...
In the first code excerpt, on line 1, "this" is of type myclass.state.momento and not myclass.state. Since myclass.state.momento and myclass.state are not related in any way the cast is not allowed, that is, one should be a parent or a child class of the other which is not the case here.
In the second code excerpt, neonlight is a subclass of class light which makes the explicit cast possible.
Note that in the first code, we deal with inner classes which are not related (no inheritance) while in the second all classes are at the same "level" but hierarchically related (inheritance relationship).
[ June 13, 2002: Message edited by: Valentin Crettaz ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic