Java - Anonymous Inner Class

Introduction

An anonymous inner class is a local inner class without a name.

It cannot have a constructor because it does not have a name.

You define an anonymous class and create its object at the same time.

An anonymous class is always created using the new operator as part of an expression.

Syntax

The general syntax for creating an anonymous class and its object is as follows:

new <interface-name or class-name> (<argument-list>) {
       // Anonymous class body goes here
}

The new operator is used to create an instance of the anonymous class.

The interface name or class name is an existing interface/class name.

If an interface name is used, the anonymous class implements the interface.

If a class name is used, the anonymous class inherits from the class.

<argument-list> is used only if the new operator is followed by a class name.

It is empty for creating anonymous class from interface.

<argument-list> contains the actual parameter list for a constructor of the existing class.

An Anonymous Class Example

Demo

public class Main {
  public static void main(String[] args) {
    new Object() {
      // An instance initializer
      {/*from w w w . java 2  s  . c  om*/
        System.out.println("Hello from an anonymous class.");
      }
    }; // A semi-colon is necessary to end the statement
  }
}

Result

Related Topics