Sign in

JAVA’s Inner Anonymous Class vs Lambda — The thin line

Inner class were added in Java 1.1, while Lambda availability came only in version 1.8 together with many cool features.
The following article will discuss the differences between those features.

Runnable r = () -> System.out.println(“I ran”)
Runnable r = new Runnable() {
public void run() {
System.out.print(“I ran”);
}
}
class RunnableImpl implements Runnable {
public void run() {
System.out.print(“I ran”);
}
}
Runnable r = new RunnableImpl() ;

1. Inheritress

2. Interfaces

3. Variables

4. Using ‘this’

class A {
int counter = 0;
public void myFunc() {
Callable r = () -> this.counter++;
r.call()
}
}
class A {
public void myFunc() {
int counter = 0;
Callable r = () -> this.counter++; <<< WILL NOT WORK
r.call()
}
}

5. .class file, reflection and class modification

6. Memory

Function f = (a + b) -> a*b
class A {
// The following must be define in the class level
int myFuncTotal = 0;
public void myFunc() {
List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5);
arr.stream().forEach(a -> myFuncTotal + a);
}
}

Please assist with sharing this article, share you gratitude by comment/applaud and feel free to share your note so we can approve the article.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store