this Keyword in Java


The this keyword refers to the current instance of a class and can be used to access class methods and variables.

Source Code

public class Rectangle {
    private int x, y;
    
    Rectangle(int x, int y) {
        this.x = x; // Refers to the instance variable x
        this.y = y; // Refers to the instance variable y
    }

    void displayInfo() {
        System.out.println("x: " + this.x + ", y: " + this.y);
    }
}

public class TestThis {
    public static void main(String[] args) {
        Rectangle rect = new Rectangle(5, 10);
        rect.displayInfo();
    }
}

Use this to differentiate between class fields and parameters with the same name, and to invoke other constructors in the same class.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments