I want to ask you why we need inner classes and why we use them ?
I know how to use inner classes but I don't know why..
Some inner classes are exposed publicly (eg Map.Entry
in Java) but that is by far the exception rather than the norm.
Inner classes are, basically, an implementation detail.
For example, Swing makes extensive use of inner classes for event listeners. Without them you would end up polluting the global namespace with a bunch of classes you otherwise don't need to see (which may make their purpose harder to determine).
Essentially inner classes are a form of scope. Package access hides classes from outside the package. Private inner classes hide that class from outside that class.
Inner classes in Java are also a substitute for a lack of function pointers or method delegates (which are in C#) or closures. They are the means of passing a function to another function. For example, in the Executor
class you have:
void execute(Runnable r);
so you can pass a method in. In C/C++ that could be achieved with:
void execute(void (*run)());
being a pointer to a function.
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