Skip to content

What is the meaning of "this" in Java?

In Java, the this keyword refers to the current object. It is used to refer to the instance variables and methods of the current object from within the object's own methods.

Here is an example of how this is used in Java:


java
public class Person {
    private String name;
    private int age;

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

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

    public void setAge(int age) {
        this.age = age;
    }

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

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

In this example, the this keyword is used to refer to the instance variables name and age.

The this keyword is also used to pass the current object as an argument to a method or constructor. For example:


java
public class Person {
    private String name;
    private int age;

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

    public void printPerson() {
        System.out.println(this);
    }

    public String toString() {
        return "Person[name=" + name + ",age=" + age + "]";
    }
}

In this example, System.out.println(this) implicitly invokes the toString() method to convert the current Person object into a string representation.

To actually pass the current object as an argument, you can call another method with this:

java
public class Person {
    private String name;
    private int age;

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

    public void printPerson() {
        logPerson(this);
    }

    private void logPerson(Person p) {
        System.out.println(p);
    }
}

Additionally, this() can be used for constructor chaining to call one constructor from another:

java
public class Person {
    private String name;
    private int age;

    public Person(String name) {
        this(name, 0); // Calls the two-argument constructor
    }

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

I hope this helps. Let me know if you have any questions.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.