this Keyword
The keyword this refers to the current class instance. For example, if a class defines a method named Calculate, you can call that method from another method within the same class like this:
this.Calculate();
Of course, you can also call the Calculate method without the this keyword:
Calculate();
Thus, in most cases, the keyword this is not necessary.
However, sometimes the this keyword can come in handy. For example:
public class Actor
{
string lastName;
string firstName;
public Actor(String lastName, String firstName)
{
this.lastName = lastName;
this.firstName = firstName;
}
}
The this keywords are required to distinguish among the parameters named lastName and firstName and the instance.
Sometimes, you use the this keyword by itself to pass a reference to the current object as a method parameter. You can print the current object to the console by using the following statement:
System.out.println(this);
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access