Shadowing field names and this
By making use of the this
keyword, you can even use the same name for arguments to the
constructor (or any other method) as you use
for field names. For example,
class TwoDPoint {
double x;
double y;
TwoDPoint(double x, double y) {
this.x = x;
this.y = y;
}
String getAsString() {
return "(" + this.x + "," + this.y + ")";
}
void setX(double x) {
this.x = x;
}
void setY(double y) {
this.y = y;
}
double getX() {
return this.x;
}
double getY() {
return this.y;
}
}
}
Inside a method, a declaration of a variable or argument
with the same name as a field shadows the field.
You can refer to the field by prefixing its name with this.
Previous | Next | Top
Last Modified September 3, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu