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?
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();
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With