This keyword in Java | Method, Reference, constructor, a​nd examples

What is “This” Keyword?

Java “this” Keyword works as a reference to the current Object in the program. In can be used in inside the Method or constructor of Java Class.

This keyword in Java

Where use This keyword in Java?

Here is list of this keyword can used to:-

  • Refer instance variable of current class.
  • Invoke or initiate current class constructor.
  • Passed as an argument (Parameters) in the method call.
  • Passed as argument (Parameters) in the constructor call.
  • Return the current class instance.

Java this keyword program example code

Let’s see the simple this keyword used in java programs or how to use it.

Instance Variable | Field

In this example using ‘this’ keyword to refer current class instance variables.

See below code how to using this.num2 and this.num2 in constructor.

Output:

Number 1 = 12 Number 2 = 10

“this” keyword in Java method

Many teams to use this keyword with java methods. Let’s see one by one with examples.

1. Use ‘this’ keyword as method parameter

Output:

Number 1 = 20 Number 2 = 0

2. Use ‘this’ keyword to invoke current class method

this keyword can be used inside Methods to call another Method in the same Class.

Output:

Show Method
Message Method

In a constructor used “this” Keyword

How to invoke current class constructor?

Using this keyword word to invoke the current class constructor. See below example program of Java “this” in the constructor.

Output:

Parameterized constructor
Default constructor

Get The class instance of Using ‘this’ keyword

Let’s see the example of get the current instance of a class using a method.

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java this keyword examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.