Difference between Anonymous Inner Class and Lambda Expression | Code Factory

Code Factory
2 min readApr 17, 2020

Reference Link : Link

Donate : Link

Anonymous Inner Class

Anonymous Inner Class is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.

package com.codeFactory;/**
* @author code.factory
*
*/
public class AnonymousClass {
public static void main(String... args) {
Name name = new Name() {

@Override
public void getName() {
System.out.println("Name : " + name);
}
};
name.getName();
}
}
interface Name {
String name = "Code Factory";
void getName();
}

Lambda Expressions

Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces.

lambda expressions are added in Java 8 and provide below functionalities.

  • Enable to treat functionality as a method argument, or code as data.
  • A function that can be created without belonging to any class.
  • A lambda expression can be passed around as if it was an object and executed on demand.
package com.codeFactory;/**
* @author code.factory
*
*/
public class LambdaExpressions {
public static void main(String... args) {
Name name = (x) -> System.out.println("Name : " + x);
name.getName("Code Factory");
}
}
interface Name {
void getName(String name);
}

Difference :

--

--