What is the this keyword in Java?

this is a reference to the object whose method or constructor is running.

  • this.name = name; separates a field from a parameter of the same name.
  • this(...) calls another constructor of the same class.
  • return this; allows method chaining.
class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    Point move(int dx) {
        this.x += dx;
        return this;
    }
}

public class Main {
    public static void main(String[] args) {
        Point p = new Point(1, 2).move(5).move(10);
        System.out.println(p.x + "," + p.y);
    }
}
Output

16,2

See Java static and this.


Learn more about the similar topics:
Tutorials
Java Classes and Objects
Java Constructors
Java static and this Keywords
Java Encapsulation and Access Modifiers
Java Inheritance
Java Polymorphism
Java Abstract Classes
Exercises & Assignments
Build a BankAccount class
Calculate areas with inheritance and polymorphism
Use a sealed interface and pattern matching
Interview Questions & Answers
What is a class and an object in Java?
What is a constructor in Java?
What is the difference between a constructor and a method in Java?
What is the this keyword in Java?
What is the static keyword in Java?
What is the final keyword in Java?
What are the four pillars of OOP in Java?