DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections
  • Projections/DTOs in Spring Data R2DBC

Trending

  • Agentic AI for Automated Application Security and Vulnerability Management
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • How to Practice TDD With Kotlin
  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  1. DZone
  2. Coding
  3. Java
  4. Java 8 — Functional Interfaces (SAM)

Java 8 — Functional Interfaces (SAM)

Going in depth with Java 8's concept of functional interfaces, and how that affects classes and objects.

By 
Hari Kiran G user avatar
Hari Kiran G
·
Apr. 07, 16 · Tutorial
Likes (27)
Comment
Save
Tweet
Share
48.6K Views

Join the DZone community and get the full member experience.

Join For Free

There are numerous interfaces in the Java library that declare a single abstract method; few such interfaces include:

// in java.lang package
interface Runnable { void run(); }

// in java.util package
interface Comparator<T> { boolean compare(T x, T y); }

// java.awt.event package:
interface ActionListener { void actionPerformed(ActionEvent e); }

// java.io package
interface FileFilter { boolean accept(File pathName); }

Java 8 has introduced the concept of “functional interfaces” that formalizes this idea. A functional interface specifies only one abstract method. Since functional interfaces specify only one abstract method, they are sometimes known as Single Abstract Method (SAM) types or interfaces.

Note: Functional interfaces can take generic parameters, as in the Comparator<T> and Callable<T> interfaces in the above examples.

For an interface to be treated as a functional interface, it should have only one abstract method. However, it may have any number of default or static methods defined in it. Let us see an example from the Java library to understand this.

Here is the definition of java.util.function.IntConsumer interface (without annotations and javadoc comments):

public interface IntConsumer {
  void accept(int value);
  default IntConsumer andThen(IntConsumer after) {
Objects.requireNonNull(after);
return (int t) -> { accept(t); after.accept(t); };
  }
}

Though this interface has two members, andThen method is a default method and only accept method is an abstract method. Hence, IntConsumer interface is a functional interface.

@FunctionalInterface Annotation

The Java compiler infers any interface with a single abstract method to be a functional interface. However, you can tag functional interface with @FunctionalInterface annotation to affirm that. It is a recommended practice to provide @FunctionalInterface to functional interfaces because the compiler can give better errors/warnings when you have this annotation.

Here is an example of using @FunctionalInterface that has one abstract method, so it will compile cleanly:

@FunctionalInterface
public interface AnnotationTest {
int foo();
}

How about this one?

@FunctionalInterface
public interface AnnotationTest {
default int foo() {};
}

It results in a compiler error “no abstract method found in interface” because it only has a default method provided but does not have any abstract methods. 

Methods From Object Class in Functional Interfaces

According to the Java Language Specification (version 8.0), “interfaces do not inherit from Object, but rather implicitly declare many of the same methods as Object.” If you provide an abstract method from Object class in the interface, it still remains a functional interface.

For example, consider the Comparator interface that declares two abstract methods:

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
    // other methods are default methods or static methods and are elided
}

This interface is a functional interface, though it declares two abstract methods: compare() and equals() methods. How is it a functional interface when it has two abstract methods? Because equals() method signature matches from Object, and the compare() method is the only remaining abstract method, hence the Comparator interface is a functional interface.

How about this interface definition?

@FunctionalInterface
interface EqualsInterface {
   boolean equals(Object obj);
}

The compiler gives the error: “EqualsInterface is not a functional interface: no abstract method found in interface EqualsInterface”. Why? Since the method equals is from Object, it is not considered as a functional interface. Check out this book for more learning about functional interfaces. You can download the source code here

Interface (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections
  • Projections/DTOs in Spring Data R2DBC

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!