Java this keyword

In Java, the this keyword refers to the current instance of a class. It is used within an instance method or constructor to refer to the current object of the class. It helps to distinguish between instance variables (fields) and parameters or local variables with the same name, and is also used to call one constructor from another in the same class.

uses of this keyword:

1. Referring to instance variables: When method or constructor parameters have the same name as instance variables, this is used to refer to the instance variables.

2. Invoking other constructors: In a constructor, this() can be used to call another constructor in the same class.

3. Passing the current object: You can pass the current object as a parameter to another method or constructor.

Example:


class Employee {
    // Instance variables
    String name;
    int age;

    // Constructor with parameters
    Employee(String name, int age) {
        // Using 'this' to refer to the instance variables
        this.name = name;
        this.age = age;
    }

    // Method to display information
    void displayInfo() {
        // Using 'this' to refer to the current object
        System.out.println("Name: " + this.name);
        System.out.println("Age: " + this.age);
    }

    // Constructor calling another constructor in the same class
    Employee(String name) {
        // Calling another constructor using 'this()'
        this(name, 18);  // Default age is 18
    }

    public static void main(String[] args) {
        // Creating an object using the first constructor
        Employee emp1 = new Employee("John", 35);
        emp1.displayInfo();

        // Creating an object using the second constructor
        Employee emp2 = new Employee("Tom");
        emp2.displayInfo();
    }
}

Output:

Name: John
Age: 35
Name: Tom
Age: 18

Explanation:

1. Constructor with this.name and this.age: In the constructor Employee(String name, int age), the parameters name and age are assigned to the instance variables name and age using this.name and this.age. This differentiates the instance variables from the parameters that have the same name.

2. Constructor call using this(name, 18): In the constructor Employee(String name), the this() constructor call invokes the other constructor Employee(String name, int age) with a default age of 18.