Anonymous Classes

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();
}

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();
}

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;

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");
      }
    });

  }
}
Home 
  Java Book 
    Class  

Nested Classes:
  1. Nested Types
  2. Nonstatic Member Classes
  3. Anonymous Classes
  4. Local Classes