What does the this keyword refer to, and why do you need it when a field and a parameter share a name?
The this keyword refers to the current object. It is the object that the method was called on, and you use it to say "this object" instead of naming it some other way.
public class Main {
public static void main(String[] args) {
Product p = new Product("Book", 20.0);
System.out.println(p);
}
}
And why do you need it when a field and a parameter share the name? Because inside the method both names refer to the parameter, and the parameter hides the field. So this.name is the field and name is the parameter.
public class Product {
private final String name;
private final double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return this.name + " costs " + this.price;
}
}
And there is another use that is worth knowing about, and it is the more important one. You can use this to call another method on the same object, and you can pass the current object to another method.
public class Product {
private final String name;
private final double price;
private boolean discounted;
public void applyDiscount(double rate) {
// This calls markDiscounted on this same object.
this.markDiscounted();
}
private void markDiscounted() {
this.discounted = true;
}
public void addTo(Order order) {
// This passes the current object to the order.
order.add(this);
}
}
And there is one more use that is quite neat. You can call another constructor of the same class with this(...), and it has to be the first statement. That way you have one real constructor and the others delegate to it.
public class Product {
private final String name;
private final double price;
public Product(String name) {
this(name, 0.0);
}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
}
So the rule to remember is this. The this keyword is the current object, and it is how you tell a field apart from a parameter that has the same name.
The last question in this topic is about when you leave it out.