What are anonymous inner classes 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.

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:11:11
Advertisements