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

Java Java Objects Delivering the MVP Forum

What does the "this" keyword refer to?

CodeExample: public class Point { public int x = 0; public int y = 0;

//constructor
public Point(int x, int y) {
    this.x = x;
    this.y = y;
}

}

So in this code does this "this.x" refer to "public int = 0;" or the "int x" within the parameter of the constructor Point.

2 Answers

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

when you call the constructor of this class, you are creating a Point object. Each Point has an x and a y coordinate. This refers to the object itself, so when you create your first Point, say at (4,5), its x will be 4 and its y will be 5. So this.x means that this object's x coordinate will be what you pass in for the x for that object. When you create your second Point, this will refer only to the second Point.

Fatemah Tavakoli
Fatemah Tavakoli
13,797 Points

The "this" keyword refers to the current context. It is mostly used to differentiate between the fields of the object and the passed parameters in case they have matching names.