Use of this Keyword in Java

In this class, We discuss the Use of this Keyword in Java.

The reader should have prior knowledge of the class and object. Click Here.

We take an example and understand the “this” keyword.

Example:

The below diagram shows the example program.

First, we understand the “this” keyword.

Heap Space is allocated for the object ob.

We reference the object using the keyword “this.”

Java Virtual machine will automatically reference the present object to “this” keyword.

In the above example, Both instance and constructor variables are the same names.

Whenever we call the constructor, p is considered a local variable.

We must consider p as an instance variable in the statement p=p.

The left side p is the instance variable.

To consider instance variables, we use the “this” keyword.

this.p = p

To differentiate local variables from instance variables, we use the “this” keyword.

The below diagram shows the example.

We can use the “this” keyword to call the class constructors and methods.

The below diagrams show an example of calling the present class constructor.

In the second constructor, we call the first constructor using the “this()” keyword.

The below diagram shows an example of calling present class methods.

In the above example, we use this.m1 to call the method “m1”.

“JVM automatically places this” keyword before method names during method calls.