Java This Keyword

Naveen AnamaneniUpdated · 5 min read

In a class photo, "me" means a different person depending on who's speaking. Inside an instance method or constructor, Java has a word that means "the object I'm working on right now": this. Every call on an object quietly carries that object along, and this lets the code refer to it directly.

this Is the Current Object

this always means the object the code is running for
ThisDemo.java▶ Try it
public class ThisDemo {
    static class Ticket {
        String name;
        int berth;
 
        Ticket(String name, int berth) {
            this.name = name;
            this.berth = berth;
        }
 
        String describe() {
            return this.name + " in berth " + this.berth;
        }
    }
 
    public static void main(String[] args) {
        Ticket t1 = new Ticket("Navika", 23);
        Ticket t2 = new Ticket("Srihitha", 24);
        System.out.println(t1.describe());
        System.out.println(t2.describe());
    }
}
Output
Navika in berth 23
Srihitha in berth 24

How it works

  1. In the constructor, the parameters name and berth have the same names as the fields. On its own, name means the parameter (it shadows the field). this.name means the field of the object being built.
  2. When t1.describe() runs, this is t1; when t2.describe() runs, this is t2.
  3. In describe, this. is optional, because no parameter shadows the fields; writing just name means the same thing.

Try it yourself: change line 7 to name = name;. What does t1.describe() print now, and why?

The Five Uses of this

UseExampleWhy
1. Tell a field from a parameterthis.name = name;The parameter hides the field
2. Call another constructorthis(name, 0);Constructor chaining (see "Constructor Overloading and Constructor Chaining")
3. Pass the current objectregister.add(this);Hand yourself to another method or object
4. Return the current objectreturn this;Method chaining, as in builders
5. Call another method on yourselfthis.validate();Optional, but sometimes clearer

Returning this for Chaining

Order.java▶ Try it
public class Order {
    static class Cart {
        int total;
        int items;
 
        Cart add(int price) {
            total += price;
            items++;
            return this;
        }
 
        Cart discount(int percent) {
            total -= total * percent / 100;
            return this;
        }
    }
 
    public static void main(String[] args) {
        Cart cart = new Cart().add(340).add(165).add(190).discount(10);
        System.out.println(cart.items + " items, Rs. " + cart.total);
    }
}
Output
3 items, Rs. 626

Each method returns this, the same Cart, so calls can be chained on one line. StringBuilder.append works exactly this way. The total is 340 + 165 + 190 = 695, minus 10% (69), giving 626.

Common Mistakes

name = name; in a constructor. It assigns the parameter to itself; the field stays null. Use this.name = name;.

Using this in a static method. There's no current object there.

Writing this. everywhere "to be safe". It's harmless, but clutters code. Use it where it adds meaning: shadowed names, chaining, passing yourself.

Interview Corner

What is the this keyword in Java?

this is a reference to the current object: the object whose constructor or instance method is running. It's used to tell fields apart from parameters with the same name, to call another constructor with this(...), to pass the current object to another method, and to return the current object for method chaining.

Can this be used in a static method?

No. Static methods belong to the class and run without any object, so there's no current object for this to refer to.

Practice

  1. Easy: Write a Student constructor whose parameters have the same names as the fields, and use this to set them.
  2. Harder: Add chainable methods addMark(int m) and bonus(int points) to a Score class, each returning this, and call them in one line.

Quick check: this

4 questions
1What does this refer to inside an instance method?
2Why write this.name = name; in a constructor?
3What does return this; enable?
4Can this be used inside main?

Key Takeaways

Was this tutorial helpful?

Lesson 104 of 482