Over the last week, I have been working with Java multi-threading in great detail. During this time, I started passively working with anonymous classes, all the while, without realizing that this was yet another worthwhile Java concept.
Anonymous classes enable you to write programs that are concise. While a regular class has a name, anonymous classes don't. Just look at the following segment of code:
Thread t = new Thread ( new Runnable() {
public void run () {
/*do something */
}
});
Now, we can see that the Thread constructor is passed an instantiated Runnable with the action to be performed in tact and encapsulated in the "run" method.
What we are in fact doing is creating an instance of a class that implements the Runnable interface and then declaring and defining the methods of this class. This is the idea of anonymous class. It's particularly useful if you do not wish to instantiate a class more than once.
No comments:
Post a Comment