00:00

this Keyword in Java – Uses and Examples

Last updated: 7 min read

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.

UseSyntax
1. Access a field hidden by a parameter or local variablethis.name = name;
2. Call another method of the current objectthis.validate(); (usually written just validate();)
3. Call another constructor of the same classthis(text, 12);
4. Return the current objectreturn this;
5. Pass the current object as an argumentbus.register(this);
6. Refer to the enclosing object from an inner classOuter.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:

ThisFields.java
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);
    }
}
Output
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:

ThisChaining.java
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));
    }
}
Output
'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:

FluentBuilder.java
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();
    }
}
Output
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:

PassThis.java
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");
    }
}
Output
email-service received ORDER_PLACED
audit-log received ORDER_PLACED
Caution: passing 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:

Outer.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 this is a compile error ("non-static variable this cannot be referenced from a static context").
  • Before super(...) or this(...) completes in a constructor: arguments to these calls cannot use this.
  • As an assignment target: this = other; is not allowed; this is 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

  • this is a reference to the current object inside instance methods and constructors.
  • Use this.field to resolve name clashes with parameters.
  • this(...) calls another constructor and must come first.
  • return this enables fluent method chaining; Outer.this reaches the enclosing object.
  • this cannot be used in static contexts.

Related Tutorials