Can someone tell me the purpose of inner classes, and if the pattens iterator should or is it a good idea to use inner classes?

Can someone tell me what the purpose of inner classes is? Also, when developing an iterator template, should we use inner classes? Would it be better to use inner classes?

+4
source share
3 answers

Wikipedia has a good article on the inner class .

You do not need to use 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(); } } 
+4
source

An inner class is a class that cannot exist without the class in which it is defined. In other words, if a class cannot exist without a β€œparent” class, then it must be better than the inner class This. Some (if not most) iterators are defined as inner classes because they are associated with the current instance of the parent class and must have direct access to it. Thus, for example, a ListIterator implementation (declared as an inner class) is required that is returned by List#iterator() direct access to the get() method of the current List instance.

+3
source

If you need to implement an interface as part of your business logic, but do not want it to be publicly available as part of your class, inner classes allow you to do this.

In general, since Java requires objects for everything, they are often quite useful for things like listeners in user interface programming, where you need to listen for a bunch of buttons or other inputs, you can add an anonymous inner class for each of them instead of putting a lot if then elses between one listener implementation for buttons or something else.

And no, you do not need to use them for anything.

+2
source

Source: https://habr.com/ru/post/1306001/


All Articles