Adverts
Anonymous Classes
Anonymous classes are one of the strangest constructs in the Java language and many new developers have trouble getting their head around exactly what is happening. Once anonymous classes are properly understood, however, they open a world of possibilities for quickly solving simple routine problems. The most common use of anonymous classes is with GUI development where they are attached as listeners to the various widgets. Probably the second most common use of anonymous classes is as filters and comparators. The example below shows a simple comparator:
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Comp {
public Comp() {
List<String> foo = new LinkedList<String>();
Collections.sort( foo, new Comparator<String>() {
public int compare( String s1, String s2 ) {
return s1.compareTo( s2 );
}
});
}
}
In the above example the anonymous class is an implementation of the Comparator interface that is used to order the List foo. The class is anonymous because it has no name and can't be referenced. In this situation the class is said to be used as a function object.
Anonymous classes can also be process objects such as Runnables or Threads and they can also be used in static factory methods where we want to view one object as if it is another by wrapping it in a class that implements a different interface.
Anonymous classes are a very powerful tool in the developers arsenal but it is important that they aren't over used or overly complex. A long anonymous class can quickly clutter a top level class making it difficult to see where one ends and the other begins. Generally speaking try and keep anonymous classes to a maximum of one screens worth of code or about 40 lines.
Local Classes
Local classes are by far the most uncommon class type to be used in the Java language. In fact I don't actually remember ever seeing one. For those interested an example is show below:
public class Enclosing {
public Enclosing() {
class Local {
public Local() {
System.out.println( "In local class...");
}
}
new Local();
}
}
A local class is declared inside a method body (member classes are declared inside the class). It is only accessible to the method it is declared in which makes local classes less generally useful than non-static inner classes. If used in a non-static setting they acquire a reference to their enclosing class. There are some uses for local classes in situations where there isn't an interface already defined so an anonymous class would be difficult or impossible to use.
You might like to visit Java Class Types Part I