Java - Using this Keyword with Class Name to reference outer class instance variable

Description

Using this Keyword with Class Name to reference outer class instance variable

Demo

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

  public class Inner {
    // Instance variable for Inner class
    private int value = 2;

    public void printValue() {
      System.out.println("\nInner - printValue()...");
      System.out.println("Inner: Value = " + value);
      System.out.println("Outer: Value = " + Outer.this.value);
    }//from w w w .j a va  2  s  .  c om
  }

  // Instance method for Outer class
  public void printValue() {
    System.out.println("\nOuter - printValue()...");
    System.out.println("Outer: Value = " + value);
  }

  // Another instance method for the Outer class
  public void setValue(int newValue) {
    System.out.println("\nSetting Outer's value to " + newValue);
    this.value = newValue;
  }
}

public class Main {
  public static void main(String[] args) {
    Outer out = new Outer();
    Outer.Inner in = out.new Inner();

    // Print the value
    out.printValue();
    in.printValue();

    // Set a new value
    out.setValue(3);

    // Print the value
    out.printValue();
    in.printValue();
  }
}

Result

Related Topic