1.

What are functional or SAM interfaces?

Answer»

Functional Interfaces are an interface with only one ABSTRACT method. Due to which it is also known as the Single Abstract Method (SAM) interface. It is known as a functional interface because it wraps a function as an interface or in other words a function is represented by a single abstract method of the interface.

Functional interfaces can have any NUMBER of default, static, and overridden METHODS. For declaring Functional Interfaces @FunctionalInterface annotation is optional to use. If this annotation is used for interfaces with more than one abstract method, it will generate a compiler error.

@FunctionalInterface // Annotation is optional public interface Foo() { // Default Method - Optional can be 0 or more public default STRING HelloWorld() { return "Hello World"; } // Static Method - Optional can be 0 or more public static String CustomMessage(String msg) { return msg; } // Single Abstract Method public void bar(); } public class FooImplementation implements Foo { // Default Method - Optional to Override@Overridepublic default String HelloWorld() { return "Hello Java 8"; } // Method Override@Overridepublic void bar() { System.out.println(“Hello World”);} } public static void main(String[] args) { FooImplementation fi = new FooImplementation();System.out.println(fi.HelloWorld());System.out.println(fi.CustomMessage(“Hi”));fi.bar();}


Discussion

No Comment Found