This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting this" Watch "Casting this" New topic
Author

Casting this

Vaibhav Shridish
Greenhorn

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
{
.....
((light)this).getbill(20);//2
System.out.println((light)this).billtype);//3
}


Vaibhav Shridish
Valentin Crettaz
Gold Digger
Sheriff

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,...)
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 ]

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
 
subject: Casting this
 
Similar Threads
Doubt from Khalid Mughal
Variable Shadowing
variable shadowing
Overriding Khalid example
Access