Anonymous Inner Class Vs Lamda

Kablumndl
1 min readJan 7, 2021

This is a very basic concept concept. 2 minute reading clear concept that how scope of veriable change when way of accessing method from anonymous inner class and using lamda expression.

If any variable declare in a method and this variable is using in a manner of Anonymous inner class then scope is maintianed as a local variable. below example illustrates the implementation.

interface testinterface {

public void m1();

}

public class Annoynymous {

int x = 88;

public void m2() {

testinterface i = new testinterface() {

int x = 99;

@Override

public void m1() {

System.out.println(“Value of x:” + this.x);

}

};

i.m1();

}

public static void main(String[] args) {

Annoynymous a = new Annoynymous();

a.m2();

}

Output: Value of x:99, local scope of variable is maintained.

Lets see how it can be access using Lamda and how scope of variable changed.

Now is a same code , initialized a local variable say x and calling a method using lamda expression.

@FunctionalInterface

interface testscope {

public void testScope();

}

public class AnonymousLamda {

int x = 10;

public void m2() {

testscope ts = () -> {

int x = 20;

System.out.println(“Value of x:” + this.x);

};

ts.testScope();

}

public static void main(String[] args) {

AnonymousLamda a = new AnonymousLamda();

a.m2();

}

}

Output:- Value of x:10

While accessing variable x from lamda block, you can see the scope is an instance instead of local as using in Anonymous.This is important point to note.

--

--

Kablumndl

Java Developer, Software Engineer, Spring, Spark, MicroService, PostgresSQL