Normally, I use this
in constructors only.
I understand that it is used to identify the parameter variable (by using this.something
), if i
It refers to the current instance of a particular object, so you could write something like
public Object getMe() {
return this;
}
A common use-case of this
is to prevent shadowing. Take the following example:
public class Person {
private final String name;
public Person(String name) {
// how would we initialize the field using parameter?
// we can't do: name = name;
}
}
In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this
allows us to access members of this instance, including the field.
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
}