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 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 ...
Get Sams Teach Yourself Java™ in 24 Hours, Sixth 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.