Lambda vs. Anonymous Inner Class

Lot of people think that Lambda in Java 8 is kind of a shorthand for writing the Inner Classes which is not completely true. Lets try to look with the help of examples the differences between Lambda and Anonymous Inner Classes.

1. Instance State

Anonymous Inner classes can have state in the form of class level instance variables. As you can see in the below example we have defined ‘state’ variable which is an instance variable of the Anonymous Inner class and we are using it to print the value.


But with Lambdas you can’t have state. As you can see in the code below Lambdas start from a function body itself , so you won’t be able to define the instance variable anywhere and its not allowed.


2. Number of Methods

Anonymous Inner classes can have multiple methods defined. Below is an example of it.


But since Lambdas are  just the body of the function defined in your functional interface so lambdas only have single method body , you can’t have multiple number of methods, it only implements a single method. As you can see in the example below.


3. Usage of “this” keyword

this points to the object instance for an Anonymous Inner Class as seen in the example below that when you try to access innerClassState variable you use this.innerClassState and if you would like to access the enclosing class state variable then you have to use ClassName.this. 


this used in Lambads points to the enclosing object for a lambda as you can see the output in the following example. As you can see this in Lambda express implicitly refers to the enclosing Object reference.

4. Class File Generation

Anonymous Inner Class results in a separate class file being generated. If you compile the code below you will see two classes being generated.

  1. InnerClassExample.class
  2. InnerClassExample$1.class


In case of Lambda expression there is no separate Class file that gets generated.


5. Performance

Imaging if you have hundred’s of Anonymous Inner Class , as we saw in the example above for every Anonymous Inner Class there is one class file that’s get generated so following are disadvantages of having a class file generated that is:

  1. More number of Class will lead to a bloated Jar file.
  2. Time taken to load a Jar file will also increase.
  3. Memory usage will go up because of these so many Class files generated.

So Lambdas tend to perform better than Anonymous Inner Class as they leverage a feature which was released in Java 7 that is invokedynamic.

0 comments… add one

Leave a Comment