February 5, 2011

Inner Classes in Java

Inner classes are classes defined within another class as a member of that class. The inner class code has access to members of the enclosing outer class, including those members marked private.


public class Outer {

   private int i;

   public void makeInner {
      Inner inner = new Inner();
      inner.accessOuter;
   }

   class Inner {
      public void accessOuter {
         i = 7;
         System.out.println("Outer class, i=" + i);
      }
   }

   public static void main(String[] args) {
      Outer outer = new Outer();
      outer.makeInner();

      Outer.Inner inner = new Outer().new Inner();
      inner.accessOuter();
   }
}

No comments:

Post a Comment