blog

Home / DeveloperSection / Blogs / Nested Classes in Java: Anonymous Classes

Nested Classes in Java: Anonymous Classes

Royce Roy 1810 19-May-2016

A local class without a name is called an anonymous class. If we need only a single instance of a local class, we will create an anonymous class. Typically, a local class has a name and thus a declaration. We instantiate this class using its name. This process is meaningful if we are going to make multiple objects of the class. For a single object, we need not name the class. A typical use of this is found in the implementation of GUI event listener methods. To give you an idea of how it looks, consider the following code fragment:

button.addActionListener(new ActionListener() {
                          public void actionPerformed(ActionEvent e) {
                                         System.out.println("The button was pressed!");                             }
});

 

Here, ActionListener is an interface that declares a sole method called actionPerformed. We create a new object of an anonymous class that implements the ActionListener interface. The object of this anonymous class is passed as a parameter to the addActionListener method on the button object.

Another classic example of the use of anonymous classes involves creating threads. The following small code snippet demonstrates this:

new Thread(new Runnable() {
         public void run() {
            try {
                while (true) {                    sleep(1000); System.out.print(".");
                }
           } catch(InterruptedException ex) {}
        }
}).start();

 Here, we create an object of an anonymous class that implements the Runnable interface. The Runnable interface has a sole method called run that is implemented in the preceding code. The new Thread code creates a Thread object by taking the previously created anonymous object as a parameter. Rather than assigning the created Thread object to a variable, we directly invoke its start method, and in this particular case we do not need to refer to the created Thread object further in our program code.

Another classic example of the use of anonymous classes is in Java’s Collection Framework. The following example shows how to use a Vector for storing a list of friends:

Vector friendsList = new Vector(4) { // defining anonymous inner class
{
    add("Sam");
    add("Smith");
    add("Anthony");
    add("Lisa”);
   }
};

And here is one more example of the use of anonymous classes. The program here lists all the .txt files in the folder specified on the command line. Examine how the anonymous class based on the implementation of the FilenameFilter interface is used.

import java.io.*;

public class FileNameFilterExample {
                     public static void main(String[] args) {
                             File folder = new File(args[0]);
                             String[] list = folder.list(new FilenameFilter() {                                       public boolean accept(File folder, String fileName) {                                                 return fileName.endsWith(".txt");                                       }
                             });
                             for (int i = 0; i < list.length; i++) {
                                      System.out.println(list[i]);
                             }
                     }
}
 Creating Anonymous Classes

In the above section, we saw a few examples of how to use anonymous classes. Here is the syntax for creating them:

new ClassName(ArgumentList){
               classBody
}

 Or

new interfaceName(){
      interfaceBody
Restrictions on the Use of Anonymous Classes

Here are the restrictions that apply to the use of anonymous classes:

·   An anonymous class cannot have a constructor because there is no name associated with it.

·   An anonymous class cannot define static fields, methods, or classes.

·   We cannot define nested interfaces in an anonymous class because these interfaces are implicitly static.

·   We cannot define an interface anonymously.

·    Like local classes, anonymous classes cannot be made public, private, protected, or static. In fact, in the definition of the anonymous class syntax, there is no provision for specifying any modifiers in their declarations.

Compiled Anonymous Classes

Given that an anonymous class does not have a name, what is the name assigned to its .class file? The compiler produces two files when we compile a class containing an anonymous class.

These are named:

·    EnclosingClassName.class and

·    EnclosingClassName$1.class.

In the case of having more than one anonymous class in the same enclosing class, the compiler produces the corresponding .class files for each anonymous class by assigning a unique number to it after the $ sign.

Guidelines on Using Anonymous Classes

Finally, here are some tips on where to use local classes and where to use anonymous classes. In general, you should consider using an anonymous class instead of a local class under the following conditions:

·    The class has a very short body.

·    Only one instance of the class is needed.

·    The class is used right after it is defined.

·    The name of the class does not make the code any easier to understand.


Updated 15-Mar-2018

Leave Comment

Comments

Liked By