Java - Use this Keyword to Qualify Class Name

Introduction

You can refer to an instance variable in any of the following three ways:

  • Using the simple name, such as value
  • Using the simple name qualified with the keyword this, such as this.value
  • Using the simple name qualified with the class name and the keyword this, such as QualifiedThis.this.value

Demo

class Outer {
  // Instance variable - value
  private int value = 1;

  public void printValue() {
    System.out.println("value=" + value);

    System.out.println("this.value=" + this.value);

    System.out.println("QualifiedThis.this.value=" + Outer.this.value);
  }/*ww w . j a  va2s  .c o m*/

  public void printHiddenValue() {
    int value = 2;

    System.out.println("value=" + value);

    System.out.println("this.value=" + this.value);

    System.out.println("QualifiedThis.this.value=" + Outer.this.value);
  }
}

public class Main {
  public static void main(String[] args) {
    Outer qt = new Outer();
    System.out.println("printValue():");
    qt.printValue();

    System.out.println("\nprintHiddenValue():");
    qt.printHiddenValue();
  }
}

Result

Related Topics