Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could someone tell me the purpose of Inner classes and if iterator pattens should or a good idea to use inner classes?

Tags:

java

Could someone tell me what the purpose of inner classes are? Also when designing the iterator pattern do we have to use inner classes? Would it be better to use inner classes?

like image 598
Victor Avatar asked Jan 23 '23 08:01

Victor


2 Answers

Wikipedia has a good article about the inner class.

You don't need to use the inner classes for the iterator pattern:

import java.util.*; 
public class BitSetIterator implements Iterator<Boolean> { 
    private final BitSet bitset; 
    private int index;

    public BitSetIterator(BitSet bitset) { 
        this.bitset = bitset; 
    }

    public boolean hasNext() {   
        return index < bitset.length(); 
    } 

    public Boolean next() { 
        if (index >= bitset.length()) { 
            throw new NoSuchElementException(); 
        } 
        boolean b = bitset.get(index++); 
        return new Boolean(b); 
    } 

    public void remove() { 
        throw new UnsupportedOperationException(); 
    }
}
like image 73
Kiril Avatar answered Jan 24 '23 20:01

Kiril


An inner class is a class which can't survive without the class where it is definied in. In other words, if a class can't survive without a "parent" class, then it should be better an inner class of it. Some (if not most) iterators are definied as inner classes, because they are coupled to the current instance of the parent class and needs to have direct access to it. So needs for example the ListIterator implementation (which is declared as an inner class) as returned by List#iterator() direct access to the get() method of the current instance of the List.

like image 34
BalusC Avatar answered Jan 24 '23 22:01

BalusC