Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Taebin You
4,786 PointsUsing this keyword...Help
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this
public class Point { public int x = 0; public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
} but it could have been written like this:
public class Point { public int x = 0; public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
} Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
This is from Oracle... Can someone explain this for me?
1 Answer
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsWell this keyword is just used for clarification. Use can use this for the first example.
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
// assign to member "x" the value of argument "a"
// straighforward
this.x = a;
this.y = b;
}
}
The task that you are trying to achieve is to assign to member of the class the value of variable passed as argument
In the first case, you assign value of "a" to "x", which is member
But in the second case
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int x) {
// compiler will be stumped
// assign to member "x" the value of argument "x"
// or assign to argument "x" the value of member "x" of this class
x = x;
y = x;
}
}
Without this, no one knows what do you want to do : ?
- Do you want to assign to member "x" of the class value of the argument method "x"
- OR do you want to assign to argument of the method "x" value of the member "x"
It is simply hard to explain.
this keyword is used for clarification for people and computer.
And I don't know a person that can interpret x=x line without additional information.
Taebin You
4,786 PointsTaebin You
4,786 PointsSo this keyword (this.x) refers to the int x of the Point class in this case?
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsAlexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Pointsyes.
this.xrefers to the member of the class called "x".