dzjustinli dzjustinli - 4 years ago 90
Java Question

when using this keyword inside method or constructor, does it matter the this keyword is on the left or the right of = sign

I'm new to Java and is trying to learn the concept of this keyword. My question is when using this keyword inside method or constructor, does it matter the this keyword is on the left or the right of = sign?

class Point {

public int x = 0;
public int y = 0;

public Point(int x, int y) {
x = this.x;//this on right hand side of =
this.y = y;//this on left hand side of =
}
}

Answer Source

Yes, it matters. this refers to the current object, so this.y = y sets the object's field y to the value passed into the constructor. x = this.x sets the local variable which was passed into the constructor to be equal to the value of the object's local x field. Then, when the constructor exits, that local variable goes out of scope (leaving the class's field unchanged) so there will be no net change.

You almost always want to use this.x = x, since the constructor's purpose is to initialize all the needed fields of the object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download