The this Keyword
in Java
Understand how this lets an object refer to itself, disambiguate fields from parameters, and chain constructor calls.
What Is this?
In Java, this is a reference variable that points to the current object: the specific instance whose method or constructor is currently executing. Every non-static method has an implicit this parameter provided by the JVM.
Why Does this Matter?
The Object in Memory
The Core Rule
Three Uses of this
this vs. No this
When a parameter has the same name as an instance field, Java's scope rules mean the parameter shadows the field. Without this, you are assigning the parameter to itself.
Assigns the parameter value to the instance field.
Assigns the parameter to itself. The field stays at its default value.
How to Apply this
Example 1: Disambiguating Fields
Example 2: Constructor Chaining
Example 3: Passing this
Scope: Parameter vs Field
this vs. super
Common Mistakes
Summary Table
| Syntax | Meaning | Where Allowed |
|---|---|---|
| this.field | Access instance variable | Instance methods/constructors |
| this.method() | Call instance method | Instance methods/constructors |
| this(...) | Chain to another constructor | Constructors only (first line) |
| return this; | Return current object | Instance methods |
| obj.method(this) | Pass current object | Instance methods/constructors |
Question 1 of 5
Consider the following class:
After executing Point p = new Point(5, 10);, what are the values of p.x and p.y?
Question 2 of 5
Which of the following correctly describes what this refers to in Java?
Question 3 of 5
Consider the following constructor:
What happens when this constructor is compiled?
Question 4 of 5
In which of the following contexts can the this keyword NOT be used?
Question 5 of 5
Consider the following class:
What does return this; enable a caller to do?