this keyword in java

In Java, the this keyword is a reference to the current object. It can be used to refer to instance variables and methods of the current object, or to call the current object’s constructor.

Here are some examples of how the this keyword can be used:

  1. Referring to instance variables:
public class Person {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        System.out.println(person.getName()); // output: John
    }
}

In this example, we have defined a Person class with a private instance variable called name. We have also defined a setName method that sets the value of the name variable, and a getName method that returns the value of the name variable. Inside the methods, we use the this keyword to refer to the current object’s name variable.

  1. Calling another constructor of the same class:
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name) {
        this(name, 0);
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 25);
        Person person2 = new Person("Mary");

        System.out.println(person1.getName()); // output: John
        System.out.println(person1.getAge()); // output: 25
        System.out.println(person2.getName()); // output: Mary
        System.out.println(person2.getAge()); // output: 0
    }
}

In this example, we have defined a Person class with two constructors. The first constructor takes two parameters, name and age, and sets the corresponding instance variables. The second constructor takes only one parameter, name, and calls the first constructor with age set to 0. Inside the constructor call, we use the this keyword to refer to the current object.

In summary, the this keyword in Java is a reference to the current object. It can be used to refer to instance variables and methods of the current object, or to call the current object’s constructor.

Share