File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java 8 Functional Interfaces

 
Joe Harry
Ranch Hand
Posts: 10045
3
Eclipse IDE Mac PPC Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Bartender
Pie
Posts: 4826
34
Chrome Netbeans IDE Windows
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic