Nested and Inner Classes

A class within another class is called nested classes. The following program illustrates how to define and use an inner class.

 
class Outer {
  int outer_x = 100;
  void test() {
    Inner inner = new Inner();
    inner.display();
  }
  class Inner {
    void display() {
      System.out.println("display: outer_x = " + outer_x);
    }
  }
}
public class Main {
  public static void main(String args[]) {
    Outer outer = new Outer();
    outer.test();
  }
}

Output from this application is shown here:


display: outer_x = 100

The inner class members are accessible only within the inner class and may not be used by the outer class. If you try to compile the following code, you will get error message.

 
public class Main {
  int outer_x = 100;
  // this is an inner class
  class Inner {
    int y = 10; // y is local to Inner

    void display() {
      System.out.println("display: outer_x = " + outer_x);
    }
  }

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

When compiling the code above:


D:\>javac Main.java
Main.java:13: cannot find symbol
symbol  : variable y
location: class Main
    System.out.println(y);
                       ^
1 error

You can define a nested class within the block defined by a method.

The following program defines a class inside a for loop.


public class Main {
  int outer_x = 100;
  void test() {
    for (int i = 0; i < 10; i++) {
      class Inner {
        void display() {
          System.out.println("display: outer_x = " + outer_x);
        }
      }
      Inner inner = new Inner();
      inner.display();
    }
  }
  public static void main(String args[]) {
    Main outer = new Main();
    outer.test();

  }
}

The output from this version of the program is shown here.


display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.