Java Functional Interface

copy from: https://javatechonline.com/java-functional-interface/

 Java Functional Interface has become available for us since the introduction of new features in Java 8. Needless to say, how important functional Interfaces are in Java. If we start learning the most popular feature of Java 8 : ‘The Lambda Expression’, we should at least know the basics of Functional Interfaces. However, you will get more than basics from this article.

Moreover, they also promote functional programming in Java. Without functional Interfaces, you can’t imagine to write a code of Lambda Expression and Method References. In fact, introduction of default & static methods inside an interface in Java 8 itself has completely changed the definition of Interfaces in Java. Let’s discuss our topic ‘Java Functional interface’ and other related concepts.

How many types of Interfaces are there in Java ?

Typically we have three types of Interfaces till now.
1) Normal Interface
2) Marker Interface
3) Functional Interface

Normal Interface is an interface which has either one or multiple number of abstract methods.
However, Marker Interface is an interface with no abstract method.  (Because till JDK8 an interface can have only abstract methods, no normal methods). We use it to provide a type to its sub-classes for executing some logic from other classes.
Additionally, Functional Interface is an interface which has only one abstract method. Further, it can have any number of static, default methods and even public methods of java.lang.Object class. In fact, we use it to define Lambda Expressions & Method References by directly providing logic to an argument of a method.

If you want to learn interfaces in java in detail, kindly visit our separate article on ‘Java Interface‘, which includes new changes in interfaces after the introduction of Java 8 & Java 9 features.

What is a Java Functional Interface?

If an interface contains only one abstract method, we call it a functional interface. The contained method is called functional method or single abstract method (SAM). Consequently, they provide target types for lambda expressions and method references. Moreover, Java 8 contains some built-in Functional Interfaces designed for commonly occurring use cases. They are available in a separate package java.util.Function. Hence, we don’t have to create our own functional interfaces every time for a small use case. Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

Note : In addition to single abstract method, we can also have any number of default & static methods inside a Functional Interface. Moreover, we don’t have any restrictions on including ‘Object’ class’ public methods inside Functional interfaces. Needless to say, they are equals(), hashCode(), notify(), notifyAll(), toString(), wait(), getClass() .

Is it not mandatory to add abstract keyword during method declaration in functional interface as we generally do in interfaces before JDK 1.8?

Obviously, It is not mandatory to add abstract keyword during the method declaration either in a java functional interface or in a normal java interface. Even, before JDK 1.8 also, it was optional. When we apply interface keyword before the name of the Interface, all methods declared in this interface become public abstract by default. Therefore, it’s up to the developer whether he/she adds it or not.

Why Java Functional Interface? Advantages of Java Functional Interface?

We provide implementation of Functional Interfaces using Lambda expressions & Lambda expressions can only be used in context of Functional interfaces. You can assign a lambda expression to a single abstract method (i.e. To a Functional interface). If you could assign a lambda expression to an interface containing more than one abstract method (i.e. a non functional interface), the lambda expression could only have implemented one of its methods, leaving the other methods unimplemented. That’s why Lambda expressions don’t have method name, return types etc. as it talks about a single abstract method.

Therefore, there is no point of having more than one abstract method in a Java Functional Interface as they are meant for Lambda expressions & Lambda expression could be assigned to a single abstract method.

Examples of Java Functional Interface: 

Runnable : contains only run() method
Comparable : contains only compareTo() method
ActionListener : contains only actionPerformed()
Callable : contains only call() method
ItemListener : contains only itemStateChanged() method

How to write a Java Functional Interface?

In addition to having only one abstract method, we should write @FunctionalInterface annotation in order to let the compiler know that the interface is a Functional. In fact, if you add annotation @FunctionalInterface, the compiler will not let you add any other abstract method inside it. For example, observe the below code:

复制代码
//This is a Functional Interface
@FunctionalInterface  
interface FunctionalInterface1 {
        
    public void m1();

}

//This is not a Functional Interface. This code will show compilation error
@FunctionalInterface  
interface NonFunctionalInterface2 {
        
    public void m1();
    public void m2();

}
复制代码

Behavior Of Functional Interface in the context of Inheritance

If an interface extends Functional Interface and child interface doesn’t contain any abstract method, then again child interface is also a Functional Interface.

复制代码
@FunctionalInterface  
interface A {
  public void m1();
}
        
@FunctionalInterface
interface B extends A{
            
}     
复制代码

In the child interface we are allowed to define exactly same single abstract method as it is in the parent interface as below.

 
@FunctionalInterface
interface B extends A {
	public void m1();   	
}   

In other words, the child interface will not have any new abstract methods otherwise child interface won’t remain a Functional Interface and if we try to use @FunctionalInterfaceannotation in child interface, compiler will show an error message. If we don’t use @FunctionalInterface in child interface & declare new abstract method, the compiler will consider it as a normal interface & will not show any error as below.

 
interface B extends A{
	public void m2();   	
}


Functional Interfaces in context of Lambda Expression (Functional Interfaces with Lambda Expression)

We can assign Lambda expressions to Functional Interfaces. In brief, if we have an interface with a single abstract method or a functional interface, then we can use the concept of lambda. This is a prerequisite to apply the concept of Lambdas. Now let’s look at the code below:

复制代码
interface A {
  public void m1();
}

public class Demo implements A{
  public void m1(){
  System.out.println("m1() is executing");
  }
} 

public class Test {
  public static void main(String[] args){
     A a= new Demo();
     a.m1();
  }
}
复制代码

We can write equivalent code to the above code using lambda expression as below:

 
复制代码
interface A {
  public void m1();
}

public class Test {
  public static void main(String[] args){
     A a= ()-> System.out.println("m1() is executing");
     a.m1();
  }
}
复制代码

Example to convert traditional code to the code using Lambda Expression

Let’s take another example to convert code using lambda expressions. To illustrate, we will develop a functionality to calculate sum of two numbers to understand use of Lambda expressions.

Without Lambda Expression:

复制代码
interface Sum {
    public void sum(int a, int b);
}

class SumImpl implements Sum {
    public void sum(int a, int b) {
        System.out.println("The sum of numbers is: " + (a + b));
    }
}

class Test {
    public static void main(String[] args) {
        Sum s = new SumImpl();
        s.sum(24, 14);
    }
}
复制代码

With Lambda Expression:

复制代码
interface Sum {
    public void sum(int a, int b);
}

class Test {
    public static void main(String[] args) {
        Sum s = (a,b) -> System.out.println("The sum of numbers is: " + (a + b));
        s.sum(24, 14);
    }
}
复制代码

Is it not mandatory to add abstract keyword during method declaration in functional interface as we generally do in interfaces before JDK 1.8?

 

 

 

 

 

 

posted @   saaspeter  阅读(41)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示