Java Anonymous Classes

In this chapter you will learn:

  1. What is Java Anonymous Classes
  2. How to define an anonymous class
  3. Example - declares and instantiates an anonymous class that implements an interface

Description

An anonymous class is a class without a name and simultaneously declared. You can instantiate an anonymous class where it is legal to specify an expression.

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

Syntax

How to define an anonymous class?


abstract class People {
  abstract void speak();
}//from   ww  w .  ja va  2  s  .  c  om

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

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

The code above generates the following result.

Example

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


interface People {
  abstract void speak();
}/*from w w w  .j av  a  2s  .co 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 code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to define a local class
  2. Example - Java Local Classes
  3. How to create a local class and return it from a method