Function interface in Java

We discussed interfaces and abstract class in earlier, let’s discuss specific type of interface called functional interface. A functional interface is an interface with only one abstract method. This abstract method is implemented by class. Below is example of a functional interface, interface CustomFunctionalInterface has only one abstract method abstractMethod.

@FunctionalInterface
public interface CustomFunctionalInterface {
	public boolean abstractMethod(Integer a);
}

Notice that there is special annotation @FunctionalInterface added in Java 8 to help compile type check, if you add another abstract method in functional interface, it will throw an error.

What happens when another interface inherit functional interface? If there is no other abstract method defined in child interface, it automatically become functional interface. Child interface can have default methods and still be functional.

It’s not that the functional interfaces came in Java 8, they preexisted, example being Runnable interface mentioned above. However there are many functional interfaces like Predicate are introduced in Java 8. By virtue of their ability to pass around functionality(i.e. behavior), functional interfaces primarily enable behavior parameterization.

Functional interface and anonymous class

Anonymous class is a class without a name. Anonymous classes are created and instantiated using functional interfaces. One of the most common example is instantiating Runnable class.

public class AnonymousInnerClassTest {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("A thread created and running");
			}
		}).start();
	}
}

This does not mean that anonymous classes can only be created using functional interface, but it is less clumsy and  more understandable when using one. Notice how anonymous class is created, 

The anonymous class expression consists of the following:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface Runnable.
  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not

Let’s see an example where we are using functional interfaces.

Please share if there is something is missing or wrong. If you want to contribute to website, please reach out to us on communications@algorithmsandme.com