Java class Access field from inner class from its outer class

Question

What is the output of the following code:

class Outer {//w  ww . ja v a2  s . co  m
  int outer_x = 100;

  void test() {
    Inner inner = new Inner();
    inner.display();
  }
  class Inner {
    int y = 10; 
    void display() {
      System.out.println("display: outer_x = " + outer_x);
    }
  }

  void showy() {
    System.out.println(y); 
  }
}

public class Main {
  public static void main(String args[]) {
    Outer outer = new Outer();
    outer.test();
  }
}


Compile time error

  void showy() {
    System.out.println(y); //y is not accessible here
  }
}

Note

An instance of Inner can be created only in the context of class Outer.

An inner class instance is often created by code within its enclosing scope.

An inner class can access all of the members of its enclosing class, but the reverse is not true.

Members of the inner class are known within the scope of the inner class and may not be used by the outer class.

Here, y is declared as an instance variable of Inner.

Thus, it is not known outside of that class and it cannot be used by showy().




PreviousNext

Related