AI Hints
Home›Java Tutorial›The this Keyword, Instance Methods and static
Java · Lesson 67 of 120

The this Keyword

This object.

⏱ 2 min read▶ Video at 1:24:09🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Inside a class, the word this means the current object. The one whose method, or constructor, is running right now.

  • this
  • The current object
  • The one running now

this dot field

It's natural to give parameters the same name as the fields. But then, which title is which? This dot title means the field of this object. Plain title means the parameter. And this, with brackets, calls another constructor, of the same class.

Main.javajava
public class Book {
    String title;
    int pages;

    Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }

    Book(String title) {
        this(title, 100);
    }
}

Using it

The second constructor passes the title on, with a hundred pages. Run it. Both books are set up correctly.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Book a = new Book("Dune", 412);
        Book b = new Book("A Short Story");
        System.out.println(a.title + ": " + a.pages);
        System.out.println(b.title + ": " + b.pages);
    }
}
Output
Dune: 412
A Short Story: 100
Also uses Book.java
public class Book {
    String title;
    int pages;

    Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }

    Book(String title) {
        this(title, 100);
    }
}

Forgetting this

Here we forgot this. Title equals title just copies the parameter into itself. The field never changes. Run it. The title is null! This is a very common bug.

Book.javajava
public class Book {
    String title;

    Book(String title) {
        title = title;
    }

    public static void main(String[] args) {
        Book b = new Book("Dune");
        System.out.println("Title: " + b.title);
    }
}
Output
Title: null

Summary

This means the current object. This dot field avoids confusion with parameters. And this, with brackets, calls another constructor. Next, methods that belong to objects.

Key takeaways
  • this.field
  • this(...)
  • Avoid shadowing bugs
Next up: Instance Methods — what an object can do