In Java, this is a reserved reference variable that refers directly to the current object—the instance whose method or constructor is actively executing on the thread stack.
this in JavaWhen a constructor parameter or method parameter has the exact same name as an instance variable, the local parameter "shadows" the instance variable. Prepending this. tells the compiler to access the object's instance variable:
public class Product {
private String name;
private double price;
public Product(String name, double price) {
// Without 'this', 'name = name' assigns parameter to itself (No effect!)
this.name = name; // Assigns parameter to instance field
this.price = price; // Assigns parameter to instance field
}
}
this()Used to delegate initialization tasks across constructors (as explored in Class 21):
public Product(String name) {
this(name, 0.0); // Calls the two-argument constructor
}
this to Enable Method Chaining (Fluent API)Returning this allows developers to chain multiple configuration method calls in a readable pipeline:
public class QueryBuilder {
private String query = "";
public QueryBuilder select(String fields) {
this.query += "SELECT " + fields + " ";
return this; // Returns current instance
}
public QueryBuilder from(String table) {
this.query += "FROM " + table + " ";
return this;
}
public QueryBuilder where(String condition) {
this.query += "WHERE " + condition;
return this;
}
public String build() {
return this.query;
}
public static void main(String[] args) {
// Method Chaining in action:
String sql = new QueryBuilder()
.select("id, username, email")
.from("users")
.where("status = 'ACTIVE'")
.build();
System.out.println("Generated SQL: " + sql);
}
}
Exam Question: "Can we reassign the this reference variable (e.g. this = new MyClass();)?"
Answer: No! this is an immutable, final reference maintained internally by the JVM runtime. Attempting to assign any value to this results in a fatal compiler error: cannot assign a value to final variable this.
Now let us explore Inheritance, superclass hierarchies, and the super keyword. Proceed to: Java Inheritance & 'super' Keyword →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Constructor chaining with this().
Using this in setters.
Comparing this with super.
Builder pattern with method chaining.