How are anonymous (inner) classes used in Java?


An inner class declared without a class name is known as an anonymous inner class.

  • we declare and instantiate them at the same time.
  • In general, they are used whenever you need to override the method of a class or an interface.

Syntax

AnonymousInner an_inner = new AnonymousInner() {
   public void my_method() {
      ........
      ........
   }
};

Example

Live Demo

abstract class AnonymousInner {
   public abstract void mymethod();
}
public class Outer_class {
   public static void main(String args[]) {
      AnonymousInner inner = new AnonymousInner() {
         public void mymethod() {
            System.out.println("This is an example of anonymous inner class");
         }
      };
      inner.mymethod();
   }
}

Output

This is an example of anonymous inner class

Updated on: 30-Jul-2019

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements