Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,258 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.