TExcelTAD
Home › Java › Java this Keyword

Java this Keyword

Inside an instance method or constructor, the keyword this is a reference to the current object — the object the method was called on, or the object being built. It has four common uses:

Use Example
refer to a field hidden by a parameter this.name = name;
call another constructor of the same class this(0, 0);
pass the current object to another method registry.add(this);
return the current object (method chaining) return this;

Fields vs. parameters with the same name

It's common — and readable — to give constructor parameters the same names as the fields they initialise. But inside the constructor, the parameter shadows the field: a plain name means the parameter. this.name reaches past it to the field.

java · try it yourself
class Student {
    String name;
    int grade;

    Student(String name, int grade) {
        this.name = name;      // field = parameter
        this.grade = grade;
    }
}

class Main {
    public static void main(String[] args) {
        Student s = new Student("Lena", 11);
        System.out.println(s.name + " is in grade " + s.grade);
    }
}
Lena is in grade 11

The classic mistake

Forget this and the assignment just copies the parameter onto itself. The field keeps its default value:

java · try it yourself
class Student {
    String name;

    Student(String name) {
        name = name;           // assigns the parameter to itself!
    }
}

class Main {
    public static void main(String[] args) {
        Student s = new Student("Lena");
        System.out.println("name = " + s.name);
    }
}
name = null

Tip: Most IDEs flag name = name as a "self-assignment" warning. Taking that warning seriously saves a lot of debugging.

Calling another constructor with this(...)

java · try it yourself
class Color {
    int r, g, b;

    Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    Color(int grey) {
        this(grey, grey, grey);    // reuse the main constructor
    }

    String hex() {
        return String.format("#%02x%02x%02x", r, g, b);
    }
}

class Main {
    public static void main(String[] args) {
        System.out.println(new Color(255, 165, 0).hex());
        System.out.println(new Color(128).hex());
    }
}
#ffa500
#808080

Passing and returning this

Returning this from a method lets callers chain several calls in one statement — a style called a fluent interface. StringBuilder.append works exactly this way. You can also pass this to another object so it knows who is talking to it:

java · try it yourself
class Email {
    String to = "";
    String subject = "";
    String body = "";

    Email to(String to) {
        this.to = to;
        return this;
    }

    Email subject(String subject) {
        this.subject = subject;
        return this;
    }

    Email body(String body) {
        this.body = body;
        return this;
    }

    void send(Outbox outbox) {
        outbox.accept(this);
    }
}

class Outbox {
    int count = 0;

    void accept(Email e) {
        count++;
        System.out.println("Queued #" + count + " to " + e.to + ": " + e.subject);
    }
}

class Main {
    public static void main(String[] args) {
        Outbox outbox = new Outbox();
        new Email().to("team@example.com").subject("Stand-up moved").body("Now 10:30").send(outbox);
        new Email().to("ada@example.com").subject("Lunch?").send(outbox);
    }
}
Queued #1 to team@example.com: Stand-up moved
Queued #2 to ada@example.com: Lunch?

Where this is not available

this only makes sense when there is a current object. In a static method there isn't one, so this can't be used there:

java
class Main {
    int value = 3;

    public static void main(String[] args) {
        System.out.println(this.value);   // error: non-static variable this cannot be referenced from a static context
    }
}

Test yourself

In a constructor Car(String model) { ... } with a field model, how do you assign the parameter to the field?

  1. model = model;
  2. this.model = model;
  3. model = this.model;
  4. Car.model = model;

What does a method that ends with return this; enable?

  1. Recursion
  2. Method chaining
  3. Static access
  4. Multiple inheritance

Can this be used inside a static method?

  1. Yes, always
  2. Only in main
  3. No, there is no current object
  4. Only to call constructors