Search code examples
javaiteratorinner-classesaccess-modifiers

Accessibility of inner class members from enclosing class


I thought members of an inner class, even when declared private, is accessible from its enclosing class. But I am running into compile time error with the following code structure. My top level class implements Iterable interface. The Iterator is implemented in an inner class. When an instance of the inner class is obtained through the iterator() method, I am not able to access the data field with that instance.

public class RandomQueue<Item> implements Iteralbe<Item>
{
     public RandomQueue() {}            
     public Iterator<Item> iterator()        // iterator() method
     { 
         return new ShuffleIterator();
     }
     // inner class implementing iterator
     private class ShuffleIterator implements Iterator<Item>  
     {
         private int i;      // private data field in inner class.
         .......
         public boolean hasNext()  {...}
         public Item next()   {...}
         public void remove()  {...} 
     }

     public void doSomething()
     {
         // Compile time error. "i cannot be resolved or is not a field"
         int j = iterator().i;     
     }
}

Any suggestions?


Solution

  • Because the return type of your method iterator() is Iterator<Item>, and you don't have any variable i in the class Iterator<Item>.

    If your method was:

     public ShuffleIterator iterator()        // iterator() method
         { 
             return new ShuffleIterator();
         }
    

    Then you will not have any compile error as i exist in the ShuffleIterator class.