Here's an example of how an anonymous inner class, a local inner class, and a regular inner class might be present in a program. The example is looking at a myMethod method and a InnerClass class present in MyClass class. For the sake of discussion, those classes will all be implementing the Runnable interface:
public class MyClass
{
public void myMethod()
{
// Anonymous inner class
Runnable r = new Runnable() {
public void run() {}
};
// Local inner class
class LocalClass implements Runnable
{
public void run() {}
}
}
// ... //
// Inner class
class InnerClass implements Runnable
{
public void run() {}
}
}
The anonymous inner class can be used to simply to make an class that implements Runnable without actually having to write out the class and naming it, and as krosenvold mentioned in his post, it is used as a "poor man's closure" in Java.
For example, a very very simple way to start a Thread using an anonymous inner class would be:
new Thread(new Runnable() {
public void run()
{
// do stuff
}
}).start();
An local inner class can be used to make a class that is within the local scope -- it won't be able to be accessed from other methods outside of myMethod.
If there was another method and we tried to make an instance of the LocalClass that is located inside the myMethod method, we won't be able to do so:
public void anotherMethod()
{
// LocalClass is out of scope, so it won't be found,
// therefore can't instantiate.
new Thread(new LocalClass()).start();
}
They allow you to take logic out of the parent class and objectify it. This removes functionality from where it doesn't belong and puts it into its own class. But what if this new object is only needed for a short time, only for the duration of a single block of code? Well, that's where a local class fits in.