What does the this keyword refer to, and why do you need it when a field and a parameter share a name?
this is a reference to the current instance. Inside any instance method or constructor, it refers to the object the code is running on, and it lets you reach that object's members explicitly.
public class Main {
public static void main(String[] args) {
Product p = new Product("Book", 20.0);
System.out.println(p);
Product q = new Product("Pen", 5.0);
System.out.println(q);
}
}
class Product {
private final String name;
private final double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
public String toString() { return name + " @ " + price; }
}You need it when a local variable or parameter shadows a field. A parameter named name and a field named name are different things, and inside the constructor the simple name always resolves to the nearer one, the parameter. Writing this.name says unambiguously that the left hand side is the field on this object. Without it, the product would be assigned its own parameter and the field would keep its default value, which is exactly the kind of silent bug that survives review because every individual line looks reasonable.
The same reasoning applies to method calls. Calling an overloaded method without qualification picks the version that matches the current scope, and this.method() forces the instance version, which matters when a subclass shadows a method with the same signature.
The interesting exception is in a constructor that delegates to another constructor. There, this refers to the object under construction but you may not use it as a value, and the delegating call has to be the first statement. In a static context there is no current instance at all, so this is a compile error there.