What are the SAM Interfaces in Java?


An interface having only one abstract method is known as a functional interface and also named as Single Abstract Method Interfaces (SAM Interfaces). One abstract method means that either a default method or an abstract method whose implementation is available by default is allowed. The instances of SAM interfaces are java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator and java.util.concurrent.Callable. The SAM interfaces can be implemented using lambda expressions or method references.

Syntax

@FunctionalInterface
public interface Changeable {
 public void change(T o);
}

Example

@FunctionalInterface
interface MyInterface {
   String reverse(String n);
}
public class LambdaReverseTest {
   public static void main( String[] args ) {
      MyInterface myInterface = (str) -> { // Lambda Expression
         String result = "";
         for(int i = str.length()-1; i >= 0 ; i--)
            result += str.charAt(i);
         return result;
      };
      System.out.println("The reverse of string is: " + myInterface.reverse("TutorialsPoint"));
   }
}

Output

The reverse of string is: tnioPslairotuT

Updated on: 13-Jul-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements