Java - Member Inner Class Having the Same Instance Variable Name as Its Enclosing Class

Description

Member Inner Class Having the Same Instance Variable Name as Its Enclosing Class

Demo

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

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

    public void printValue() {
      System.out.println("Inner: Value = " + value);
    }//from  w  w w .  j a  va2 s  . c om
  } // Inner class ends here

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

  // Another instance method for Outer class
  public void setValue(int 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