From the course: Advanced Java Programming

Functional interfaces in Java - Java Tutorial

From the course: Advanced Java Programming

Start my 1-month free trial

Functional interfaces in Java

- [Instructor] In Java 8, a new feature was introduced called lambdas. Lambdas represent the implementation of a functional interface. So before learning how to implement lambdas, it's as useful to understand what a functional interface is. A functional interface is an interface that has only one abstract method. In this example, I have a simple interface called greeting message. The interface has a single abstract method called greet which takes one argument of type string called name. I have added the annotation functional interface above the name of the interface. To show that it conforms to the rules of a functional interface. If I try and add another method, for example, public abstract void test, I get an error where the annotation is declared. This tells me that my greeting message interface is no longer a functional interface because there are multiple non-overriding abstract methods. So I will remove the test method and the error disappears. Now I can implement the functional interface in another class. Here I have a class called main with a main method in it. Inside the main method, I can create a new instance of greeting message which I will call gm. Then I will put that this is equal to a new greeting message instance. When I do this, NetBeans automatically adds an override version of the greeting method. Because greeting message has an abstract method with no implementation, I have to add my own every time I create a new instance of greeting message. This is also known as an anonymous in a class. I will replace NetBeans automatic implementation with a print statement that prints out hello and the name that was passed in. Now I can call the method by writing gm.greet and I will pass in my name, Bethan. Now when I run the program, it prints out hello Bethan to the console. That is all the functional interface is. It allows Java programmers to pass code around as data. At the moment, the codes to implement my functional interface is quite long and messy considering all it does is provide one new line of functionality. Lamdas were introduced to improve this.

Contents