this Keyword in Java – Uses and Examples
Inside an instance method or constructor, the keyword this refers to the current object: the object whose method is running. It lets code say "my own field", "my own method" or "me" explicitly.
This tutorial covers the six main uses of this with examples: accessing fields hidden by parameters, calling methods, calling another constructor with this(...), returning the current object for method chaining, passing the current object to another object, and reaching an outer object from an inner class.
1. What Does this Refer To?
When you call p.rename("Asha"), Java runs rename with this set to the object p. A different object calling the same method gets its own this. You can think of this as a hidden parameter that every instance method receives.
| Use | Syntax |
|---|---|
| 1. Access a field hidden by a parameter or local variable | this.name = name; |
| 2. Call another method of the current object | this.validate(); (usually written just validate();) |
| 3. Call another constructor of the same class | this(text, 12); |
| 4. Return the current object | return this; |
| 5. Pass the current object as an argument | bus.register(this); |
| 6. Refer to the enclosing object from an inner class | Outer.this.field |
2. Use 1: Distinguish Fields from Parameters
When a parameter has the same name as a field, the parameter shadows the field. this.name refers to the field; plain name refers to the parameter:
public class ThisFields {
private String name;
private int age;
ThisFields(String name, int age) {
this.name = name; // this.name = the field, name = the parameter
this.age = age;
}
void rename(String name) {
name = name.trim(); // without "this", this line changes only the parameter
this.name = name;
}
@Override public String toString() { return name + " (" + age + ")"; }
public static void main(String[] args) {
ThisFields p = new ThisFields("Asha", 28);
System.out.println(p);
p.rename(" Asha Verma ");
System.out.println(p);
}
}
Asha (28) Asha Verma (28)
Forgetting this. in a constructor (name = name;) is a classic bug: it assigns the parameter to itself and leaves the field unchanged.
3. Use 2: Call Methods of the Current Object
Inside an instance method, validate() and this.validate() mean the same thing. The explicit form is rarely needed, but it can make code clearer when passing a method reference, such as this::handle.
4. Use 3: Call Another Constructor with this(...)
Overloaded constructors can delegate to each other, keeping the initialisation logic in one place. this(...) must be the first statement in the constructor:
public class ThisChaining {
private final String text;
private final int size;
private final boolean bold;
ThisChaining(String text) { this(text, 12); } // this(...) calls another constructor
ThisChaining(String text, int size) { this(text, size, false); }
ThisChaining(String text, int size, boolean bold) {
this.text = text;
this.size = size;
this.bold = bold;
}
@Override public String toString() { return "'" + text + "' size " + size + (bold ? " bold" : ""); }
public static void main(String[] args) {
System.out.println(new ThisChaining("Hello"));
System.out.println(new ThisChaining("Title", 24, true));
}
}
'Hello' size 12 'Title' size 24 bold
See Constructor Chaining.
5. Use 4: Return this for Method Chaining
Methods that return this let callers chain calls in one fluent statement, a style used by builders and APIs such as StringBuilder:
public class FluentBuilder {
static class Email {
private String to = "", subject = "", body = "";
Email to(String to) { this.to = to; return this; } // return this enables chaining
Email subject(String s) { this.subject = s; return this; }
Email body(String b) { this.body = b; return this; }
void send() { System.out.println("To: " + to + " | Subject: " + subject + " | " + body); }
}
public static void main(String[] args) {
new Email().to("asha@example.com").subject("Welcome").body("Thanks for joining!").send();
}
}
To: asha@example.com | Subject: Welcome | Thanks for joining!
6. Use 5: Pass the Current Object
An object can hand itself to another object, for example to register as a listener:
import java.util.ArrayList;
import java.util.List;
public class PassThis {
static class EventBus {
private final List<Listener> listeners = new ArrayList<>();
void register(Listener l) { listeners.add(l); }
void publish(String event) { for (Listener l : listeners) l.onEvent(event); }
}
static class Listener {
private final String name;
Listener(String name, EventBus bus) {
this.name = name;
bus.register(this); // pass the current object to another object
}
void onEvent(String event) { System.out.println(name + " received " + event); }
}
public static void main(String[] args) {
EventBus bus = new EventBus();
new Listener("email-service", bus);
new Listener("audit-log", bus);
bus.publish("ORDER_PLACED");
}
}
email-service received ORDER_PLACED audit-log received ORDER_PLACED
this from a constructor lets other code see the object before it is fully initialised ("this-escape"). Prefer registering after construction, for example in a factory method, especially in multithreaded code.7. Use 6: Outer.this in Inner Classes
Inside an inner (non-static nested) class, this means the inner object. To reach the enclosing object, write OuterClassName.this:
class Counter {
int count = 10;
class Printer {
int count = 1;
void print() {
System.out.println(count); // 1 (inner field)
System.out.println(Counter.this.count); // 10 (outer object's field)
}
}
}
8. Where this Cannot Be Used
- Static methods and static blocks: there is no current object, so
thisis a compile error ("non-static variable this cannot be referenced from a static context"). - Before
super(...)orthis(...)completes in a constructor: arguments to these calls cannot usethis. - As an assignment target:
this = other;is not allowed;thisis fixed.
In lambdas, this refers to the enclosing object (not the lambda), while in anonymous classes it refers to the anonymous class instance.
9. Summary
thisis a reference to the current object inside instance methods and constructors.- Use
this.fieldto resolve name clashes with parameters. this(...)calls another constructor and must come first.return thisenables fluent method chaining;Outer.thisreaches the enclosing object.thiscannot be used in static contexts.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is the this keyword in Java?
A reference to the current object, available inside instance methods and constructors.
Q2. Why do we use this.name = name in constructors?
The parameter name shadows the field. this.name explicitly refers to the field, so the parameter value is stored in it.
Q3. Can this be used in a static method?
No. Static methods belong to the class, not to an object, so there is no current object to refer to.
Q4. What is the difference between this and this()?
this refers to the current object. this(...) calls another constructor of the same class and must be the first statement of a constructor.
Q5. What is the difference between this and super?
this refers to the current object and its class's members. super refers to the parent class's members and constructors, for example to call an overridden method's parent version.
Q6. Can this be assigned a new value?
No. this is final and always refers to the current object.
Q7. Why would a method return this?
To support method chaining, such as builder.setA(1).setB(2).build(), which makes configuration code compact and readable.
Q8. Can I pass this as an argument?
Yes, for example to register the current object as a listener. Avoid doing it in constructors, because the object is not fully initialised yet.
Q9. What is Outer.this?
Inside an inner class, Outer.this refers to the enclosing instance of class Outer, letting you reach its fields when names are shadowed.
Q10. Is this required to call instance methods?
No. doWork() and this.doWork() are the same inside an instance method. The explicit form is optional.
Q11. What does this mean inside a lambda?
The same as in the surrounding code: the enclosing object. Lambdas do not create their own this, unlike anonymous classes.
Q12. What does this mean inside an anonymous class?
The instance of the anonymous class itself. Use Outer.this to refer to the enclosing object.
Q13. Can this be null?
No. Inside an instance method, the method could only be called on an existing object, so this always refers to that object.
Q14. Can I use this in a record?
Yes, in instance methods and constructors of a record, just like in a class. Records commonly use this in compact constructors for validation logic.
Q15. Is using this.field everywhere good style?
It is a matter of style. Many teams use it only when needed to resolve shadowing; others use it consistently for clarity. Be consistent within a codebase.
Q16. What happens if I forget this in a setter?
void setName(String name) { name = name; } assigns the parameter to itself, and the field never changes. IDEs warn about this.
Q17. Can this() and super() both be used in one constructor?
No. A constructor can start with either one, but not both.
Q18. What is the "this-escape" problem?
Letting a reference to this leave a constructor (for example by registering a listener) before construction finishes. Other code may then see a partially initialised object. Java 21's compiler can warn about it with -Xlint:this-escape.
Q19. How many uses does the this keyword have?
Commonly six: referring to fields, calling methods, calling constructors with this(...), returning the current object, passing it as an argument, and reaching an outer object with Outer.this.
Q20. Can this be used in an interface default method?
Yes. In a default method, this refers to the object implementing the interface, so you can call its other interface methods.