How are anonymous (inner) classes used in Java?

Java 8Object Oriented ProgrammingProgramming

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

raja
Published on 08-Jan-2018 07:26:45
Advertisements