Anonymous Classes

In this chapter you will learn:

  1. How to define an anonymous class

Syntax for anonymous class

An anonymous class is a class without a name and simultaneously declared. It is not a member of its enclosing class. You can instantiate an anonymous class where it is legal to specify an expression.

abstract class People {
  abstract void speak();
}/*  j a v  a 2 s.c o  m*/

public class Main {
  public static void main(final String[] args) {
    new People() {
      String msg = "test";

      @Override
      void speak() {
        System.out.println(msg);
      }
    }.speak();
  }
}

An anonymous class instance can only access local final variables and final parameters.

The following code declares and instantiates an anonymous class that implements an interface

abstract class People {
  abstract void speak();
}//from   j a v a 2s.  c  o m

public class Main {
  public static void main(final String[] args) {
    new People() {
      String msg = (args.length == 1) ? args[0] : "nothing to say";

      @Override
      public void speak() {
        System.out.println(msg);
      }
    }.speak();
  }
}

The following example creates an anonymous class using the java.io package's File and FilenameFilter classes:

import java.io.File;
import java.io.FilenameFilter;
//from   ja va 2 s .  c  o  m
public class Main {
  public static void main(final String[] args) {
    String[] list = new File("c:/").list(new FilenameFilter() {
      @Override
      public boolean accept(File f, String s) {
        return s.endsWith(".java");
      }
    });

  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to define a local class
  2. How to create a local class and return it from a method