Why make private inner class member public in Java?

前端 未结 7 1976
情深已故
情深已故 2020-12-02 15:54

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?

publi         


        
7条回答
  •  自闭症患者
    2020-12-02 16:17

    It is useful when you implement any interface.

    class DataStructure implements Iterable {
    
        @Override
        public Iterator iterator() {
            return new InnerEvenIterator();
        }
        // ...        
    
        private class InnerEvenIterator implements Iterator {
            // ...    
            public boolean hasNext() { // Why public?
                // ...
                return false;
            }
    
            @Override
            public DataStructure next() {
                throw new UnsupportedOperationException("Not supported yet.");
            }
    
            @Override
            public void remove() {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        }
    
        public static void main(String[] ex) {
            DataStructure ds = new DataStructure();
            Iterator ids = ds.iterator();
            ids.hasNext(); // accessable            
        }
    }
    

提交回复
热议问题