Java - Class this keyword

What is this keyword?

Java keyword this is a reference to the current instance of a class.

this can be used only in class instance.

Example

The following code uses this to access the current class.

public class Main {
        int varA = 555;
        int varB = varA;      // Assign value of varA to varB
        int varC = this.varA; // Assign value of varA to varC
}

The following code uses this to access the instance variable shadowed by local variable.

Demo

public class Main {
  int num = 0; // An instance variable

  void printNum(int num) {
    System.out.println("Parameter num: " + num);
    System.out.println("Instance variable num: " + this.num);
  }/*  w w w . j  ava  2 s . c  o m*/

  public static void main(String[] args) {
    Main tt6 = new Main();
    tt6.printNum(1);
  }
}

Result

Related Topics

Quiz