Member-only story
Understanding this: A Guide to Java Constructors
Why fields get shadowed, and how this helps you reference them correctly
What is this keyword in Java?
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.
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
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
class Point{
int x, y;
Point(int x, int y){
x=x;
y=y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
class Main {
public static void main(String[] args) {
Point point = new Point(1,2);
System.out.println("x value is "+point.getX());
System.out.println("y value is "+point.getY());
}
}In the example above, the fields x and y are shadowed by the constructor parameters.










