7

我在探索 Java 8 的特性时遇到了“Functional Interface”

据我了解,这些接口可以有一些默认实现的方法:

@FunctionalInterface
public interface ComplexFunctionalInterface extends SimpleFuncInterface 
{
    default public void doSomeWork()
    {
        System.out.println("Doing some work in interface impl...");
    }
    default public void doSomeOtherWork()
    {
        System.out.println("Doing some other work in interface impl...");
    }
}

但我的疑问是,这就是抽象类的用途。

为什么要引入功能接口

4

5 回答 5

15

但我的疑问是,这就是抽象类的用途。

为什么要引入功能接口。

可扩展的类数:1

可实现的接口数:more than 1

于 2013-11-13T09:30:39.390 回答
3

Functional interface are is used in a "safe" multiple inheritance. Differences:

  • A class may extend multiple functional interfaces.
  • Functional interfaces may have only a single abstract method.
  • Functional interfaces may not have fields unlike C++ abstract classes.

Typical usage is when you want to embed default functionality into objects. I.e. if you have a function-like object,

class MyFunction1 {
    public Integer apply(String s){
        ...
    }
}

class MyFunction2 {
    public List<String> apply(Integer s){
        ...
    }
}

And you want to make a composition out of them, you just drop in implements Function:

class MyFunction1 implements Function<String, Integer>{
    public Integer apply(String s){
        ...
    }
}

class MyFunction2 implements Function<Integer, List<String>>{
    public List<String> apply(Integer s){
        ...
    }
}

And you may create a composition of your functions. Two approaches compared:

No functional interfaces:

MyFunction1 myFunction1 = ...;
MyFunction2 myFunction2 = ...;

Function<String, List<String>> composition = (s) -> myFunction2.apply(myFunction1.apply(s));

With functional interfaces:

MyFunction1 myFunction1 = ...;
MyFunction2 myFunction2 = ...;

Function<String, List<String>> composition = myFunction1.andThen(myFunction2);

The difference

  • No need to re-implement functions.
  • Other functions available in the extending class: compose and identity.
  • New default function is made a part of a class hierarchy and there is no need to create a new object. Usually functions like compose() are not included into a class definition as it would result into class size growth. They are often put into separate utility classes. In Guava composition is put into a separate utility class Functions: Functions.compose. So with new functional interfaces you would not need to recall in which utility class your function is implemented.
于 2013-11-13T10:14:19.303 回答
1

功能接口必须只有一种方法。唯一的例外是在 Object 中声明的方法。见http://java.dzone.com/articles/introduction-functional-1

于 2013-11-13T09:34:24.220 回答
0

接口 Comparator 是函数式的,尽管它显式声明了两个方法,因为只有一个是抽象的;equals 是从 Object 继承的具体方法的显式声明,如果没有此声明,否则将被隐式声明。

于 2013-11-13T09:33:26.137 回答
0

我还没有使用 JAVA 8 的经验,但据我所知,这将允许一种多重继承,这对于抽象类是不可能的

于 2013-11-13T09:30:57.477 回答