Why make private inner class member public in Java?

vitaut picture vitaut · Jun 7, 2011 · Viewed 28.4k times · Source

What is the reason of declaring a member of a private inner class public in Java if it still can't be accessed outside of containing class? Or can it?

public class DataStructure {
    // ...

    private class InnerEvenIterator {
        // ...

        public boolean hasNext() { // Why public?
            // ...
        }
    }
}

Answer

Gursel Koca picture Gursel Koca · Jun 7, 2011

If the InnerEvenIterator class does not extend any class or implement any interface, I think it is nonsense because no other class can access any instance of it.

However, if it extends or implements any other non private class or interface, it makes sense. An example:

interface EvenIterator {
    public boolean hasNext();
}


public class DataStructure {
    // ...

    private class InnerEvenIterator implements EvenIterator{
        // ...

        public boolean hasNext() { // Why public?
            // ...
        }
    }

    InnerEvenIterator iterator;

    public EvenIterator getIterator(){
         return iterator;
    }     

}