1
votes

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?

2
The type Iterator does not have an accessible field named i. What do you think you're accessing with iterator().i?Sotirios Delimanolis
I am hoping to implement the Iterator so it iterates through an array and shuffle it while doing so. Therefore I added in some data fields and methods apart from the interface abstract methods. iterator().someDataField needs to return the results of shuffling operation.Muye
To be clear: this is not about inner classes, nor is it about private.user253751

2 Answers

2
votes

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.

2
votes

Your method iterator

 public Iterator<Item> iterator()        // iterator() method

is declared to return a value of type Iterator<Item>.

The type Iterator does not have an accessible field named i.

Your ShuffleIterator does. Either cast the returned value or change the return type.