Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use inner classes?

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..

like image 969
Mohamad Alhamoud Avatar asked Apr 25 '10 09:04

Mohamad Alhamoud


1 Answers

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.

like image 86
cletus Avatar answered Oct 02 '22 15:10

cletus