Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

this
keyword
java

What is the 'this' keyword in Java?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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);
}
svg viewer
'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);
        }
}

RELATED TAGS

this
keyword
java
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring