Classes/Objects  «Prev 


Java Outer Inner Class

An inner class is referenced using the name of its enclosing class or interface, followed by a period, followed by the inner class name.
For example, if an inner class named Inner is declared inside a class named Outer, it is referenced as Outer.Inner. However, there is a catch in this naming scheme. The actual class name used by the JVM is Outer$Inner. This naming scheme was used to minimize the changes required to the JDK 1.02 virtual machine in order to handle inner classes. Inner classes fall under the same restriction as top-level classes in that they may not take the name of a package.

To see an inner class in use, let's first consider an array. In the following example, we will create an array, fill it with integer values and then output only values of even indices of the array in ascending order.
The DataStructure class below consists of:
The DataStructure outer class, which includes methods to add an integer onto the array and print out values of even indices of the array. The InnerEvenIterator inner class, which is similar to a standard Java iterator. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element. A main method that instantiates a DataStructure object (ds) and uses it to fill the arrayOfInts array with integer values (0, 1, 2, 3, etc.), then calls a printEven method to print out values of even indices of arrayOfInts.

public class DataStructure {
   // create an array
   private final static int SIZE = 15;
   private int[] arrayOfInts = new int[SIZE];
   
   public DataStructure() {
       // fill the array with ascending integer values
       for (int i = 0; i < SIZE; i++) {
           arrayOfInts[i] = i;
       }
   }
   
   public void printEven() {
       // print out values of even indices of the array
       InnerEvenIterator iterator = this.new InnerEvenIterator();
       while (iterator.hasNext()) {
           System.out.println(iterator.getNext() + " ");
       }
   }
   
   // inner class implements the Iterator pattern
   private class InnerEvenIterator {
       // start stepping through the array from the beginning
       private int next = 0;
       
       public boolean hasNext() {
           // check if a current element is the last in the array
           return (next <= SIZE - 1);
       }
       
       public int getNext() {
           // record a value of an even index of the array
           int retValue = arrayOfInts[next];
           //get the next even element
           next += 2;
           return retValue;
       }
   }
   
   public static void main(String s[]) {
       // fill the array with integer values and print out only
       // values of even indices
       DataStructure ds = new DataStructure();
       ds.printEven();
   }
}