What is the 'this' keyword in Java?

The this keyword in Java is a reference variable which points (or refers) to the current instance of a class. The keyword resolves any ambiguity between a parameter and member variable of the same name. Its uses are the following:

1. Accessing member variables or functions

The this keyword can be used to call functions and access member variables of the current instance. There are situations when the name of a variable, which is a member of a class, is the same as that of the parameter. In such a case, using the this keyword is mandatory with the variable which is a member of the class; otherwise, the program won’t compile.

public void setName(String fName, String lName){
        this.fName = fName;
        this.setLastName(lName);
}
'this' keyword resolves ambiguity
'this' keyword resolves ambiguity

2. Passing the instance

We can pass the current instance to another function using the this keyword. It may be a constructor or a normal function:

class Person{
        Animal pet;
        Person(Animal a){
                a = pet;
        }
}

class Animal{
        String colour;
        String name;
        Person owner;
        public Animal(String colour){
                this.colour = colour;
        }
        public Animal(String colour, String name){
                this.colour = colour;
                this.name = name;

                // passing itself to the constructor
                owner = new Person(this);
        }
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved