File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting this" Watch "Casting this" New topic

Casting this

Vaibhav Shridish

Joined: Jun 06, 2002
Posts: 28
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

Vaibhav Shridish
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
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,...)
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 ]

[Blog] [Blogroll] [My Reviews] My Linked In
I agree. Here's the link:
subject: Casting this
It's not a secret anymore!