Skip to content

Functional Interface

Pranav V R edited this page Jun 23, 2024 · 1 revision

A functional interface in Java is an interface that contains only a single abstract (unimplemented) method. A functional interface can contain default and static methods.

Also known as SAM (Single abstract method) interface.

public interface MyFunctionalInterface {

    public void execute();
}
public interface MyFunctionalInterface2{
    
    public void execute();

    public default void print(String text) {
        System.out.println(text);
    }

    public static void print(String text, PrintWriter writer) throws IOException {
        writer.write(text);
    }
}

@FunctionalInterface annotation is introduced in java8. But functional interfaces are there in java from initial version. Annotation is not mandatory.

If annotation is there in interface and user adds more than one abstract method to that interface then compiler throws exception Multiple non overriding abstract methods found

Some commonly used examples of functional interfaces are below.

  • Runnable - contains only run abstract method
  • Comparable - contains only compareTo abstract method
  • Comparator - contains only compare abstract method and may default and static methods

Clone this wiki locally