Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

In general, I use this in constructors. “This” keyword is a way to identify the parameter variable (like this. something) when it has the same name as the global variable.

But, I want to know what’s the exact meaning of this in Java and how the code will work if I use this without dot (.)? 

1 Answer

0 votes
by (19.7k points)

“This” is used to refer to the current object. An object is needed to call a non-static method. So, when you have a class like this:

public class MyPractice{

  private int myVar;

  public MyPractice() {

    this(42); // calls the other constructor

  }

  public MyPractice(int a) {

    this.myVar = myVar; // assigns the value of the parameter myVar to the field of the same name

  }

  public void myMethod() {

    int myVar = 1;

    System.out.println(myVar); // refers to the local variable myVar

    System.out.println(this.myVar); // refers to the field myVar

    System.out.println(this); // refers to this entire object

  }

  public String toString() {

    return "MyPractice myVar=" + myVar; // refers to the field myVar

  }

}

When you call  myMethod() on new MyPractice(), it will print

1

42

MyPractice myVar=42

Hence, “this” can be used in multiple scenarios

  1. To denote the field variable, when there’s another variable with the same name. 

  2. To denote the current object

  3. To invoke other constructors of the current class. 

Interested in Java? Check out this Java Certification by Intellipaat.  

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 14, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Feb 18, 2021 in Java by Jake (7k points)

Browse Categories

...