Donate : Link
Medium Blog : Link
Applications : 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 :
| Anonymous Inner Class | Lambda Expression |
| It is class without name | It is method without name. (Anonymous function) |
| It can extend abstract and concrete class | It can not extend abstract and concrete class |
| It can implement an interface that contains any number of abstract methods | It can implement an interface which contains a single abstract methods |
| Inside this we can declare instance variables | It does not allow declaration of instance variables, whether the variables declared simply act as local variables |
| Anonymous inner class can be instantiated | Lambda expression can not be instantiated |
| Inside Anonymous inner class, “this” always refers to current anonymous inner class object but not to outer object | Inside Lambda expression, “this” always refers to current outer class object that is, enclosing class object |
| It is the best choice if we want to handle multiple methods | It is the best choice if we want to handle interface |
| At the time of compilation, a separate .class file will be generated | At the time of compilation, no separate .class file will be generated. It simply convert it into private method outer class |
| Memory allocation is on demand, whenever we are creating an object | It resides in a permanent memory of JVM |

