0
0
Javaprogramming~5 mins

This keyword usage in Java

Choose your learning style9 modes available
Introduction

The this keyword helps you refer to the current object inside a class. It makes your code clear and avoids confusion when names overlap.

When you want to refer to the current object's fields inside a method.
When constructor parameters have the same names as class fields.
When you want to call one constructor from another in the same class.
When you want to pass the current object as a parameter to another method.
Syntax
Java
this.fieldName
this.methodName()
this(parameters)  // to call another constructor

this always refers to the current object instance.

Use this to avoid confusion between local variables and object fields.

Examples
Here, this.color means the field of the object, and color is the constructor parameter.
Java
class Car {
    String color;
    Car(String color) {
        this.color = color;  // 'this.color' is the field, 'color' is the parameter
    }
}
this.name refers to the field, so we can set it using the parameter name.
Java
class Person {
    String name;
    void setName(String name) {
        this.name = name;  // Assign parameter to the object's field
    }
}
this(10, 20) calls another constructor in the same class.
Java
class Box {
    int width, height;
    Box() {
        this(10, 20);  // Calls the other constructor
    }
    Box(int w, int h) {
        width = w;
        height = h;
    }
}
Sample Program

This program shows how this assigns the constructor parameter to the object's field and then prints it.

Java
public class ThisExample {
    int x;
    ThisExample(int x) {
        this.x = x;  // Assign parameter x to field x
    }
    void printX() {
        System.out.println("Value of x: " + this.x);
    }
    public static void main(String[] args) {
        ThisExample obj = new ThisExample(5);
        obj.printX();
    }
}
OutputSuccess
Important Notes

You cannot use this in static methods because static methods belong to the class, not an object.

Using this improves code readability and helps avoid mistakes when names overlap.

Summary

this refers to the current object instance.

Use this to access fields or methods of the current object.

this can call another constructor in the same class.