aspose file tools*
The moose likes Features new in Java 8 and the fly likes Java 8 Functional Interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Features new in Java 8
Bookmark "Java 8 Functional Interfaces" Watch "Java 8 Functional Interfaces" New topic
Author

Java 8 Functional Interfaces

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9427
    
    2

In the recent days, I have been working extensively with Scala and I was eagerly looking forward using Java again and Java 8 seems to be promising with a lot of new features. I heard a lot about functional interfaces in Java 8, but never had the time to get into it. What exactly is it? Is it the interface that we write and tell to the compiler through annotations to treat them differently than the traditional interfaces in Java? I would be interested to know more.


SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

A functional interface is an interface that has only one method. Methods that take the interface as their parameter can then be passed a lambda instead of an object reference.

The @FunctionalInterface annotation is comparable to the @Override annotation. It explains to the compiler what you're trying to do, and the compiler will help you by making sure what you're trying to do is what happens.

If you don't use the @Override annotation, the compiler will not complain if you accidentally end up writing a method that doesn't override the one declared in the super-type. This can lead to problems.

With @FunctionalInterface, you tell the compiler that the interface you're writing should be able to have lambda "instances", instead of traditional anonymous instances. If you accidentally add a second method to the interface, the compiler will complain.

A functional interface will still be a functional interface without the annotation.

For instance, Comparator is now a functional interface. Instead of doing this:
You can now do this:
Actually it's even better to do this:
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Java 8 Functional Interfaces