• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Casting this

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
}
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Willie Smits can speak 40 languages. This tiny ad can speak only one:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic