What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new
keyword, a call to a constructor and the class definition inside {
and }
.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass
used here would be user defined. This class will implement the Runnable
interface which is required for creating threads. In the ThreadClass
the run()
method (only method in Runnable
) needs to be implemented as well.
It is clear that getting rid of ThreadClass
would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task
in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread()
constructor returns an unnamed object that implements the Runnable
interface and overrides the run()
method. The method run()
would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition