SAM - Functional Interface
SAM (Single Abstract Method) is the term used to describe a functional interface in Java. SAM interfaces are often used with lambda expressions, which were introduced in Java 8. This is a type of interface that has a single abstract method, which allows you to create instances in a functional way. That is, a SAM interface has exactly one abstract method and can be implemented using lambda expressions. Here is an example below with an abstract method named run:
@FunctionalInterface
public interface IFunctionalInterface {
abstract int run(int a, int b, int c);
}
In this example above, you can add other methods, as long as they are not abstract. You can add other methods that are static and default, as well. Here is another example below:
@FunctionalInterface
public interface IFunctionalInterface {
abstract int run(int a, int b, int c);
static void secondMethod() {
System.out.println("This is a static method");
}
default void thirdMethod() {
System.out.println("This is a default method");
}
static void fourthMethod() {
System.out.println("This is a static method");
}
}
The annotation @FunctionalInterface isn't mandatory, but is recommended. It is used to ensure that the interface has only one abstract method. If you add this annotation and the interface contains more than one abstract method, the compiler will generate an error.
public class Main {
public static void main(String[] args) {
IFunctionalInterface calc = (a, b, c) -> a + b * c;
System.out.println(calc.run(2, 2, 10));
}
}
In the example above, 22 will be shown. When the interface has only one abstract method (for example, run), this method is used. In this way, we can use lambda functions.
In conclusion, Single Abstract Method (SAM) interfaces, also known as functional interfaces, are a key feature in Java that simplifies functional programming by enabling the use of lambda expressions and method references. These interfaces, characterized by a single abstract method, provide a concise and readable way to define and pass behaviors. While the @FunctionalInterface annotation is optional, its use is encouraged as it enforces the single abstract method constraint at compile time, ensuring clarity and correctness in the code. This feature, introduced in Java 8, has significantly enhanced Java's expressiveness and flexibility for modern programming paradigms.
#java #class #learn #functionalinterface #sam
Dude what u did in your talk 8 motnhs ago, it is since 2014 i mean are u serious?