The this keyword in Java refers to the object whose instance method or constructor is currently running. Use it to access that object's fields, call its methods, or pass its reference elsewhere. The related expression this(...) calls another constructor in the same class.
Its most familiar use is resolving a naming conflict. In this.code = code, the left side means the object's field; the right side means the parameter named code. Without the qualifier, a parameter can hide the field and make an assignment update nothing useful.
What is the this keyword in Java?
Imagine two bicycle passes created from one class. Each pass has its own code. When you invoke a method on the first pass, this refers to the first object. During a call on the second pass, it refers to the second object. It does not permanently name the class or whichever object was created most recently.
Java normally lets an instance method access its fields without writing this. A method can return code directly when no local declaration hides that field. Writing this.code makes the receiver explicit. That distinction becomes essential when a constructor or method parameter has the same name.
Why do we use this for matching names?
Consider code = code inside rename. Both occurrences resolve to the parameter, so the assignment merely assigns that parameter to itself. The field retains its previous value. This is a logic mistake that can compile successfully, making an output check particularly useful.
You could instead name the parameter replacementCode and write code = replacementCode. That is also valid. Use this where it clarifies the object being accessed; it is not mandatory punctuation for every field reference.
Rules for this() constructor calls
On this course's Java 17 baseline, this(...) must be the first statement in its constructor. Do not place a print, assignment or validation statement before it. Put shared validation in the constructor receiving the delegated arguments.
A constructor cannot directly or indirectly delegate back to itself forever. For example, if the no-argument constructor calls the integer constructor and that constructor calls the no-argument constructor, Java rejects the recursive invocation.
this(...) selects a constructor from the current class. super(...) selects a constructor from its superclass. A Java 17 constructor cannot explicitly invoke both as separate statements. Newer Java releases have changed some constructor-body rules, so keep the project's target version in mind.
Explicit method calls and overriding
Inside an instance method, totalDays() and this.totalDays() normally select the same receiver. The explicit form can improve clarity, but it does not change an instance call into a static call.
If the method is overridden in a subclass, a call through this can dispatch to the overriding implementation. It does not force the superclass version. Use super.methodName() when deliberately calling an accessible superclass implementation. This difference matters when a base class calls a helper that a subclass specializes.
Sharing the current object safely
Java passes argument values by value. In registry.record(this), the copied value is an object reference. The registry can reach the same object through its parameter; no pass object is cloned.
A collaborator that retains that reference may observe later changes to mutable fields. Decide whether sharing the whole object is appropriate or whether sharing a small immutable value would be simpler. Avoid publishing this from a constructor before initialization is complete: another component could encounter an object whose fields are not ready.
this versus this(): quick comparison
| Form | Meaning | Where it is useful |
|---|---|---|
| this | Current object reference | Instance methods and constructors |
| this.code | Field on that object | Resolving a shadowed field name |
| this.rename(value) | Instance method call | Making the receiver explicit |
| this(7) | Another constructor of the same class | Sharing initialization |
| registry.record(this) | Pass the current object reference | Collaborating with another object |
this itself cannot be reassigned. Writing this = anotherPass is illegal. Also, this(...) is not a general method you can call after construction to reset an object.
Java this Keyword Syntax
Java this keyword syntax
this.fieldName = parameter;
this.instanceMethod();
this(arguments); // delegate to another constructor
anotherObject.accept(this); // pass the current objectThe first, second and fourth forms use the current object reference. The third form is a special constructor invocation, with rules that differ from an ordinary method call.
Java this Keyword Summary
- this refers to the current object, while this(...) delegates to another constructor.
- Qualify a field when a local variable or parameter hides its name.
- Explicit this.method() calls still follow instance-method dispatch rules.
- Passing this shares a reference to the same object.
- Static methods need an ordinary object reference to access instance state.
- Review constructors and try the Java exercises.
Java this Keyword Examples
Each example shows the code, the output it produces and what each part does.
Using this with instance variables
Save this complete program as PassFieldExample.java. A parameter named code hides the field inside both the constructor and rename.
public class PassFieldExample {
private String code;
PassFieldExample(String code) {
this.code = code;
}
void rename(String code) {
this.code = code;
}
public static void main(String[] args) {
PassFieldExample pass = new PassFieldExample("B-18");
pass.rename("B-24");
System.out.println(pass.code);
}
}B-24Line-by-line explanation
- Line 2Each object stores its own code in an instance field.
- Lines 4 to 5Construction receives B-18 as the parameter and stores it in the newly created object's field.
- Lines 8 to 9rename receives B-24. this.code selects the same object's field, while code selects the new parameter.
- Lines 13 to 15The caller creates one pass, changes its code, and prints the updated field.
Using this() for constructor chaining
Constructor chaining keeps a default value and its initialization in one place.
public class PassConstructorExample {
private final int validDays;
PassConstructorExample() {
this(7);
}
PassConstructorExample(int validDays) {
if (validDays < 1) {
throw new IllegalArgumentException("Positive duration required");
}
this.validDays = validDays;
}
public static void main(String[] args) {
System.out.println(new PassConstructorExample().validDays);
System.out.println(new PassConstructorExample(14).validDays);
}
}7
14Line-by-line explanation
- Lines 4 to 5The no-argument constructor delegates to the constructor accepting an integer, supplying the default seven.
- Lines 8 to 12The destination constructor validates the duration before assigning the final field.
- Lines 16 to 17One call uses the default duration and the other supplies fourteen explicitly.
Calling an instance method using this
An explicit receiver can make it clear that a helper works on the current object.
public class PassMethodExample {
private final int validDays = 5;
int remainingAfter(int usedDays) {
return this.totalDays() - usedDays;
}
int totalDays() {
return validDays;
}
public static void main(String[] args) {
System.out.println(new PassMethodExample().remainingAfter(2));
}
}3Line-by-line explanation
- Lines 4 to 5remainingAfter calls totalDays on the current pass, then subtracts the supplied two used days.
- Lines 8 to 9totalDays reads the current object's five-day duration.
- Line 13The returned result is printed by the caller.
Passing this as an argument
A registry can receive the actual pass object rather than a separate copy of its code.
public class PassArgumentExample {
private final String code = "R-31";
void register(Registry registry) {
registry.record(this);
}
static class Registry {
void record(PassArgumentExample pass) {
System.out.println("Registered " + pass.code);
}
}
public static void main(String[] args) {
new PassArgumentExample().register(new Registry());
}
}Registered R-31Line-by-line explanation
- Lines 4 to 5register passes its current receiver to the registry.
- Lines 8 to 10Registry receives a reference to that same pass and reads its code.
- Line 15The caller creates the two objects and starts registration.
Why this cannot be used in a static method
The following version deliberately does not compile. A static method belongs to the class and has no current instance. The compiler reports that this cannot be referenced from a static context. Create an object and use its reference instead:
public class StaticThisError {
int validDays = 6;
public static void main(String[] args) {
System.out.println(this.validDays);
}
}public class StaticPassExample {
int validDays = 6;
public static void main(String[] args) {
StaticPassExample pass = new StaticPassExample();
System.out.println(pass.validDays);
}
}6Line-by-line explanation
- Lines 5 to 6The corrected program creates an instance and accesses its field through pass, an ordinary reference available in the static method.
Java this Keyword FAQ
Is this required in every constructor?
No. It is needed to disambiguate a hidden field or to make the current receiver explicit. Different parameter names can avoid a conflict, though matching names with this.field are common.
Can an instance method return this?
Yes. Returning this returns the current receiver's reference. Fluent APIs sometimes do this so calls can be chained; the method's return type must be compatible with the object.
How do inner classes refer to their outer object?
Inside a non-static inner class, this refers to the inner object. OuterClass.this selects its enclosing outer object. The inner classes lesson demonstrates that distinction.
Can this ever be null?
No. Inside an instance method or constructor, this always refers to a real object, because the method could only be called on an existing object. A NullPointerException happens earlier, at the call site, when the reference used to call the method is null.
What does this mean inside a lambda or an anonymous class?
Inside a lambda, this means the same as in the surrounding method: the enclosing object. Inside an anonymous class, this refers to the anonymous class's own object, and you write Outer.this to reach the enclosing one. That difference matters when converting anonymous classes into lambdas.
Java this Keyword Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
In a constructor with a parameter named code, what does this.code = code assign?
A constructor stores "Q-8". rename("Q-9") contains code = code instead of this.code = code. What remains in the field?
Java this Keyword Quiz
2 questions to check what you learned.
Which Java 17 constructor body uses legal delegation?
- A body whose first statement is this(10);
- A body that prints a message and then calls this(10);
- An instance method that calls this(10);
What does record(this) pass to its method parameter?
- A copied reference value identifying the current object
- A newly cloned object with separate fields
- The class name as a String