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?
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.
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.
上一篇: java中的内部类和外壳实例
下一篇: 来自封闭类的内部类成员的可访问性