Java Anonymous Classes

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();
}/* w  ww. ja  va  2  s  . com*/

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();
}/*  w  w  w  .j  ava 2 s  .  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 code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures