Differences between anonymous class and lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time. A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name.

Anonymous class vs Lambda Expression

  • An anonymous class object generates a separate class file after compilation that increases the size of a jar file while a lambda expression is converted into a private method. It uses invokedynamic bytecode instruction to bind this method dynamically, which saves time and memory.
  • We use this keyword to represent the current class in lambda expression while in the case of an anonymous class, this keyword can represent that particular anonymous class.
  • Anonymous classes can be used in case of more than one abstract method while a lambda expression specifically used for functional interfaces.
  • We need to provide the function body only in lambda expression while in the case of an anonymous class, we need to write the redundant class definition.

Example

public class ThreadTest {
   public static void main(String[] args) {
      Runnable r1 = new Runnable() { // Anonymous class
      @Override
      public void run() {
         System.out.println("Using Anonymous class");
      }
   };
      Runnable r2 = () -> { // lambda expression
         System.out.println("Using Lambda Expression");
      };
      new Thread(r1).start();
      new Thread(r2).start();
   }
}

Output

Using Anonymous class
Using Lambda Expression
raja
Published on 09-Dec-2019 14:18:02
Advertisements