01 / 20

Using the
this Keyword

Learn how Java's this keyword lets an object refer to itself, resolving name conflicts and enabling elegant method chaining.

Java

What is this?

In Java, this is a special reference variable that every non-static method and constructor receives automatically. It points to the current object: the specific instance on which the method was called.

Why Do We Need It?

Disambiguation
When a parameter has the same name as a field, this tells the compiler which is which.
Method Chaining
Returning this from a method lets you call multiple methods in a single fluent statement.
Passing Self
You can pass this as an argument to another method that needs a reference to the current object.

The this Reference in Memory

STACK setName("Ada") name = "Ada" this = @0x3A7 HEAP Student @0x3A7 name "Ada" gpa 3.9 year 2 points to s1 = @0x3A7

Core Rule: Disambiguation

public class Student { private String name; public void setName(String name) { this.name = name; // this.name = field // name = parameter } }

Constructors and this

public class Student { private String name; private int year; public Student(String name, int year) { this.name = name; this.year = year; } }

this.field vs. field

this.name name (alone)
No shadowing Instance field Instance field
Parameter shadows field Instance field Parameter (local)
Required? Only when shadowed Default lookup
Best practice Always in setters/constructors Fine when names differ

Intro to Method Chaining

When a method returns this, it hands the caller back a reference to the same object. That means you can call another method on the result immediately, creating a chain of calls in a single statement.

// Without chaining (verbose) student.setName("Ada"); student.setYear(2); student.setGpa(3.9); // With chaining (fluent) student.setName("Ada") .setYear(2) .setGpa(3.9);

How to Apply this

1
Check for name conflicts. Does your parameter or local variable share a name with an instance field?
2
Prefix the field with this. Write this.fieldName on the left side of the assignment to target the instance field.
3
For chaining, change the return type. Replace void with the class name as the return type.
4
Return this. Add return this; at the end of the method so the caller gets the object back.

Example 1: Basic Setter

public class Dog { private String breed; public void setBreed(String breed) { this.breed = breed; } public String getBreed() { return this.breed; // "this." optional here (no shadowing) } }

Example 2: Full Constructor

public class Rectangle { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public double area() { return this.width * this.height; } }

Example 3: Method Chaining

public class Pizza { private String size; private boolean cheese; private boolean pepperoni; public Pizza setSize(String size) { this.size = size; return this; } public Pizza addCheese() { this.cheese = true; return this; } public Pizza addPepperoni() { this.pepperoni = true; return this; } }

Chaining in Action

Pizza myPizza = new Pizza() .setSize("large") .addCheese() .addPepperoni();
setSize() returns this addCheese() returns this addPepperoni() returns this Pizza Step 1 Step 2 Step 3 Result Each method returns the same Pizza object

Common Mistakes

✕ Forgetting this in setters
Writing name = name assigns the parameter to itself. The field stays null or at its default value.
✕ Using this in static methods
Static methods belong to the class, not an instance. There is no current object, so this causes a compile error.
✕ Wrong return type for chaining
Returning this from a void method is a compile error. Change the return type to the class name.

Summary Table

Use Case Pattern Return Type
Disambiguate field from parameter this.field = param void (typical)
Constructor initialization this.field = param N/A (constructor)
Method chaining return this; ClassName
Pass self to another method other.method(this) varies
Static context Not allowed Compile error

Question 1 of 5

What does the keyword this refer to in a Java instance method?

Question 2 of 5

Given the constructor below, what value does this.color hold after new Car("red")?

public Car(String color) { color = color; }

Question 3 of 5

Which of the following correctly enables method chaining on the setter setAge?

Question 4 of 5

Why does using this inside a static method cause a compile error?

Question 5 of 5

What is printed by the following code?

public class Box { private int size; public Box(int size) { this.size = size; } public Box grow(int n) { this.size += n; return this; } public int getSize() { return size; } } // In main: Box b = new Box(5); System.out.println(b.grow(3).grow(2).getSize());