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 ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.