Anonymous Inner Class vs Lambda Function

Posted By : Hemant Samriya | 29-Jul-2021

 

* Anonymous Inner Class:

 

>It is a class without a name, which can implement an interface that contains any number of Abstract Methods. It can also extend the concrete class and abstract class.

 

> Inside Anonymous inner class, we can declare the Instance Variables, and we can use the 'this' keyword in the inner class, which points to the current inner class object but not points to the outer class object.

 

Example:

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Test{
	public static void main(String[] args){
		/*Implementing thread with Anonymous class*/
		Thread thread = new Thread(new Runnable(){
			public void run(){
				for(int i=0; i<10; i++){
					System.out.println("Child-Thread-Anonymous-Class "+ i);
				}			
			}		
		});
		thread.start();
		for(int i=0; i<10; i++){
			System.out.println("Main-Thread-Anonymous-Class "+ i);
		}
	}
}

 

* Lambda Functions :

 

> It is a method without a name, Which can implement only those interfaces that contain only one abstract form or only Functional Interface.

 

> Inside the Lambda Function, we are not able to declare instance variables. Any variable we declare in the lambda function acts like a local variable (local variable implicitly a final variable, and we can't re-assign this variable).

 

> 'this' keyword can be used in a lambda function, which points to the current outer class object reference.

 

Example:

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Test{
	public static void main(String[] args){
		/*Implementing thread with Lambda Function*/
		Thread thread = new Thread(()->{
				for(int i=0; i<10; i++){
					System.out.println("Child-Thread-Lambda-Function "+ i);
				}			
		});
		thread.start();
		for(int i=0; i<10; i++){
			System.out.println("Main-Thread-Lambda-Function "+ i);
		}
	}
}

 
> Here, we have a list, with which we can use the lambda functions-


1. Comparator
2. Predicate (Java 8)
3. Supplier (Java 8)
4. Consumer (Java 8)
5. function (Java 8)
6. Runnable
7. Collections.sort()
8. TreeMap
9. TreeSet
   and so on.


Note:

 

* Anonymous Inner Class is not equal to Lambda Function because Anonymous Inner Class contains more Powerful Features(this keyword, instance variable, etc.) than the Lambda Function. We can replace the Anonymous Inner Class with Lambda Function when only one abstract method (Functional Interface) is available. In multiple abstract methods case, we use Anonymous Inner Class to implement them, which is the best way in this case.

 

* Hence we can say Anonymous Inner Class != Lambda Functions.


References:

* https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
* https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html
* journaldev.com
* howtodoinjava.com

Request For Proposal

Sending message..

Ready to innovate ? Let's get in touch

Chat With Us