Anonymous classes enable you to make your code more concise.
They enable you to declare and instantiate a class at the same time.
They are like local classes except that they do not have a name
public interface FunctionalInterface1 {
// Functional Interface by defining Single Abstract Method in interface.
public void printMessage();
}
public class FunctionalInterface1Test {
public static void main(String[] args) {
// anonymous inner class example
FunctionalInterface1 ft1=new FunctionalInterface1(){
public void printMessage(){
System.out.println("anonymous inner class example");
}
};
ft1.printMessage();
// lambda expression example
FunctionalInterface1 ft2=()->{
System.out.println("lambda test1");
System.out.println("lambda test2");
};
ft2.printMessage();
}
}
Functional interface can not have more than one abstract method but it can have more than one default methods.
You can use annotations for functional interfaces
@FunctionalInterface
public interface FunctionalInterface2 {
// Functional Interface by defining Single Abstract Method in interface.
public void printMessage();
// public void printMessage1();
}
if you uncomment printMessage1 it gives error below
Invalid '@FunctionalInterface' annotation; FunctionalInterface2 is not a functional interface
public class FunctionalInterface2Test {
public static void main(String[] args) {
FunctionalInterface2 fi1=new FunctionalInterface2() {
@Override
public void printMessage() {
System.out.println("anonymous inner class test1");
}
};
fi1.printMessage();
FunctionalInterface2 fi2=()->{
System.out.println("lambda expression test1");
};
fi2.printMessage();
}
}
Using functional interfaces with anonymous inner classes are a common pattern in Java
In addition to the EventListener classes, interfaces like Runnable and Comparator are used in a similar manner
Therefore, functional interfaces are leveraged for use with lambda expressions.
As Runnable is having Single Abstract Method, we can consider this as a Functional Interface and we can use Lambda expression
public class RunnableTest {
public static void main(String[] args) {
System.out.println("=== RunnableTest ===");
// Anonymous Runnable
Runnable r1 = new Runnable(){
@Override
public void run() {
System.out.println("anonymous works");
}
};
// Lambda Runnable
Runnable r2=()-> System.out.println("lambda works");
// Run em!
r1.run();
r2.run();
}
}