what is this keyword in java with example

What is this keyword in java with example

In Java, the this keyword is a reference variable that refers to the current object. It is often used to differentiate instance variables from local variables when they have the same name, as well as to pass the current object as a parameter to other methods. Here are a few common uses of the this keyword with examples:

1. To Differentiate Between Instance and Local Variables:
Java
/*
 * Author: Zameer Ali
 * */
class MyClass {
    private int num; // instance variable

    void setNum(int num) {
        this.num = num; // Using this keyword to differentiate between instance and local variables
    }
}

In this example, this.num refers to the instance variable of the class, whereas num without this refers to the method parameter.

2. To Invoke Current Class Method:
Java
/*
 * Author: Zameer Ali
 * */
class MyClass {
    void display() {
        System.out.println("Hello, World!");
    }

    void callDisplay() {
        // Invoking the current class method using this keyword
        this.display(); 
    }
}

Here, this.display(); calls the display() method of the current class.

3. To Pass the Current Object as a Parameter:
Java
/*
 * Author: Zameer Ali
 * */
class MyClass {
    private int num;

    MyClass(int num) {
        this.num = num;
    }

    void compare(MyClass obj) {
        if (this.num == obj.num) {
            System.out.println("Equal");
        } else {
            System.out.println("Not Equal");
        }
    }
}

In this example, this is used to refer to the instance variable of the current object, and obj.num refers to the instance variable of the object passed as a parameter.

4. In Constructors to Call Another Constructor:
Java
/*
 * Author: Zameer Ali
 * */
class MyClass {
    private int num;

    MyClass() {
        // Calling another constructor of the same
        // class using this keyword
        this(0); 
    }

    MyClass(int num) {
        this.num = num;
    }
}

In this case, this(0); calls the parameterized constructor of the same class, passing 0 as the value for num.

The this keyword is essential in Java for maintaining object state and for avoiding naming conflicts between instance variables and local variables. It allows for clear and unambiguous reference to object members within methods and constructors.

Leave a Reply

Your email address will not be published. Required fields are marked *