Using the this Keyword

Because 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 a little more clear is with the this statement. The this statement is a way to refer in 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:

void public 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 wanted 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 wanted 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 will not be 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.

      
Comments