Java - Accessing Enclosing Class Members

Introduction

An inner class has access to all instance members, instance fields, and instance methods of its enclosing class.

Demo

class Outer {
  private int value = 1;

  // Inner class starts here
  public class Inner {
    public void printValue() {
      System.out.println("Inner: Value = " + value);
    }//from w  ww.j  a v a  2s  . co m
  } // Inner class ends here

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

  // Another instance method for the 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(2);

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

Result

Related Topics