this
KeywordBecause you can refer to variables and methods in other classes along with variables and methods in your own classes, the variable you’re referring to can become confusing in some circumstances. One way to make things more clear is with the this
statement—a way to refer within a program to the program’s own object.
When you are using an object’s methods or variables, you put the name of the object in front of the method or variable name, separated by a period. Consider these examples:
Virus chickenpox = new Virus();
chickenpox.name = "LoveHandles";
chickenpox.setSeconds(75);
These statements create a new Virus
object called chickenpox
, set the name
variable of chickenpox
, and then call the setSeconds()
method of chickenpox
.
There are times in a program when you need to refer to the current object—in other words, the object represented by the program itself. For example, inside the Virus
class, you might have a method that has its own variable called author
:
public void checkAuthor() {
String author = null;
}
A variable called author
exists within the scope of the checkAuthor()
method, but it isn’t the same variable as an object variable called author
. If you want to refer to the current object’s author
variable, you have to use the this
statement, as in the following:
System.out.println(this.author);
By using this
, you make it clear to which variable or method you are referring. You can use this
anywhere in a class that you would refer to an object by name. If you want to send the current object as an argument in a method, for example, you could use a statement such as the following:
verifyData(this);
In many cases, the this
statement is not needed to make it clear that you’re referring to an object’s variables and methods. However, there’s no detriment to using this
any time you want to be sure you’re referring to the right thing.
The this
keyword comes in handy in a constructor when setting the value of an object’s instance variables. Consider a Virus
object that has author
and maxFileSize
variables. This constructor sets them:
public Virus(String author, int maxFileSize) {
this.author = author;
this.maxFileSize = maxFileSize;
}
18.224.58.121