Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 201 ยท Object-Oriented Programming

The this Keyword

Learn what this means in Java - telling fields from parameters, the self-assignment bug, passing this to other objects, fluent APIs, this(...) and lambdas.

Inside an instance method or constructor, Java gives you a hidden variable named this. It holds a reference to the object the code is currently running for. When you call kitchen.switchOn(), this inside switchOn is kitchen; when you call hall.switchOn(), it is hall. The same method code serves every object, and this tells it which one it's working on.

You'll use this for four everyday jobs: telling a field apart from a parameter with the same name, handing the current object to another method, returning the current object so calls can be chained, and calling one constructor from another. This lesson covers all four, plus the places where this doesn't exist and the subtle way it behaves inside lambdas.

What this refers to

Every instance method receives the object it was called on, even though you never list it as a parameter. Writing this.room means "the room field of the current object". Two objects of the same class each have their own fields, and this picks the right set:

Java Which object is this?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows that hall counted its own two clicks while kitchen kept its count at one. isSameLampAs compares this with another reference using ==, which is true only when both point to the same object (see Classes and Objects for how references work).

A few facts about this:

  • Its type is the class you're writing, so this inside Lamp is a Lamp.
  • It's never null. If an object didn't exist, you couldn't be running its method.
  • It's read-only. this = other; is a compile error.

this is usually implicit

In switchOn you could drop every this. and the program would behave the same. When Java sees a name like timesSwitchedOn that isn't a local variable or parameter, it looks for a field and quietly adds this. for you. The same goes for methods: calling reset() inside another instance method means this.reset().

Most Java code leaves this. out except where it's needed. Some teams write it everywhere for clarity; both styles are fine, as long as a project picks one.

Telling fields from parameters

The most common reason to write this is a constructor or setter whose parameter has the same name as a field:

Java
class Player {
    private String name;

    Player(String name) {
        this.name = name;   // field = parameter
    }
}

Inside the constructor, the parameter name shadows the field name: the plain name now means the parameter. this.name reaches past the parameter to the field. This naming style is so common that IDEs generate it automatically, because it avoids inventing awkward names like newName or n.

The self-assignment bug

Forget the this. and the code still compiles, but it does nothing useful. It assigns the parameter to itself and leaves the field untouched:

Java A forgotten this leaves the field empty

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This prints name = null, score = 10: the field name kept its default value, null. The rename method works without this because its parameter has a different name, so name can only mean the field.

The compiler doesn't warn about name = name;. Making fields final is a good defense: a final field must be assigned exactly once in every constructor, so forgetting this. becomes a compile error ("variable name might not have been initialized") instead of a silent null.

Passing this to other objects

this is an ordinary reference, so you can pass it to methods, store it in other objects or put it in collections. Objects that point back at each other, like a folder and its parent, are built this way:

Java Children that remember their parent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

add runs on root (or docs), so this is the folder receiving the new child, and child.parent = this links the child back to it. You'll see the same pattern when an object registers itself with something else, for example button.addListener(this) or scheduler.register(this).

Don't let this escape from a constructor

Passing this out of a constructor is risky. Until the constructor finishes, the object is only partly built; any code that receives this early may see fields that are still null or 0. With threads it's worse, because another thread might use the object before it's ready. Register the object after construction instead, for example in a static factory method:

Java
static Sensor create(Hub hub) {
    Sensor sensor = new Sensor();   // fully built first
    hub.register(sensor);           // then shared
    return sensor;
}

Returning this for fluent APIs

A method that ends with return this; hands back the object it was called on, so the caller can call another method on the result right away. This is called method chaining, and APIs built around it are called fluent. You already know one: StringBuilder.append returns the same builder, which is why sb.append("a").append("b") works (StringBuilder).

Java A fluent message builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each setter-like method changes the object and returns it, so the whole message reads as one sentence. Builders, query builders and test assertion libraries use this style heavily.

Keep two cautions in mind. First, a fluent method that returns this changes the object; the immutable alternative returns a new object instead (String.trim() and LocalDate.plusDays() work that way). Second, chains get awkward with inheritance: if Message.to returns Message, a subclass UrgentMessage loses its own methods after the first call in the chain unless it overrides each method with a narrower return type (a feature you'll meet in Polymorphism).

Calling another constructor with this(...)

this(...) with parentheses is different from this the reference. It calls another constructor of the same class, so all the real setup lives in one place. The full story is in Constructors; here is the short version:

Java Constructor chaining with this(...)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rules:

  • this(...) can only appear in a constructor, at most once, and not together with super(...).
  • Until Java 25 it had to be the first statement. Java 25 (flexible constructor bodies) lets you run statements before it, like the split above, as long as they don't use the object being built: no reading its fields and no calling its instance methods.
  • Constructors can't call each other in a loop; this() in both directions is a compile error ("recursive constructor invocation").

Where this doesn't exist

this only makes sense when there's a current object. A static method belongs to the class itself and runs without any object, so this is not available there:

Java
class Counter {
    int count;

    static void resetAll() {
        this.count = 0;     // error: non-static variable this cannot be referenced from a static context
        count = 0;          // error: non-static variable count cannot be referenced from a static context
    }
}

The second line fails for the same reason: a bare field name means this.count, and there is no this. That's also why public static void main can't touch instance fields directly and has to create an object first. Static Fields, Methods and Blocks explains the static side in detail.

this in lambdas, anonymous and inner classes

Lambdas don't create a new this. Inside a lambda, this means exactly what it means in the surrounding method. An anonymous class is a real class, though, so inside its methods this is the anonymous object. To reach the outer object from an inner or anonymous class, write OuterClass.this:

Java What this means in lambdas and anonymous classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The lambda prints the Greeter because its this is the Greeter. The anonymous class prints its own generated class name, Greeter$1, and needs Greeter.this to get at the outer object. You'll meet these class kinds properly in Nested, Inner, Local and Anonymous Classes and Lambda Expressions.

Good habits

  • Use this.field = field in constructors and setters. It's the convention, and readers expect it.
  • Make fields final when they never change, so a missing this. fails to compile.
  • Return this only from methods meant for chaining, and document that they modify the object.
  • Don't pass this out of a constructor. Finish building the object first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class has a field int size; and a constructor Box(int size) { size = size; }. What is new Box(5).size?

    Inside the constructor the parameter shadows the field, so size = size assigns the parameter to itself. The field keeps its default value 0. Write this.size = size.
  2. 2. Why does this.total = 0; fail inside a static method?

    Static methods belong to the class, not to an object. There is no current object, so neither this nor bare instance field names are available.
  3. 3. What does a method need to do so callers can write order.add("tea").add("cake").place();?

    If add returns the object it was called on, the next call in the chain runs on the same order. That's the fluent style that StringBuilder.append also uses.
  4. 4. Inside a lambda written in an instance method of class Shop, what does this refer to?

    Lambdas don't introduce a new this. It means the same as in the surrounding code, here the Shop instance. Anonymous classes are different, they get their own this.
  5. 5. Which statement about this(...) is true in Java 25?

    this(...) is only for constructors. Java 25's flexible constructor bodies allow statements before it that don't touch the new object, but you still get one this(...) or super(...) call, not both.

Summary

  • this is a reference to the object the current instance method or constructor is running for; it's never null and can't be reassigned.
  • Java adds this. implicitly to bare field and method names; write it explicitly when a parameter shadows a field.
  • name = name; silently assigns a parameter to itself; final fields turn that bug into a compile error.
  • Pass this to link objects together, but not from inside a constructor.
  • return this; enables method chaining and fluent APIs.
  • this(...) calls another constructor of the same class; since Java 25, statements that don't use the new object may come before it.
  • Static methods have no this; lambdas share the enclosing this, anonymous classes have their own, and Outer.this reaches the outer object.

Next: Access Modifiers, where you'll control which code can see your fields, methods and classes.