I don’t really understand the use of ‘this’ in Java. If someone could help me clarify I would really appreciate it.
On this website it says: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
“Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.”
and it gives the following example:
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;
}
}
Yet, I still don’t fully understand why x = a could have been written as this.x = x? Why isn’t it this.x = a? Why is the x on the left side?
I’m sorry but I am very new to Java. I apologize for boring the experts.
If some variable/argument with same name as object’s property is defined, it “overlaps” the name of that property and one should use this.var_name.
So yes, it could be written as
this.x = a, but is somewhat redundant.