Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In java 8, an abstract class with only one abstract method is not a functional interface (JSR 335).

This interface is a functional interface:

public interface MyFunctionalInterface {
    public abstract void myAbstractMethod();
    public default void method() {
        myAbstractMethod();
    }
}

but this abstract class is not:

public abstract class MyFunctionalAbstractClass {
    public abstract void myAbstractMethod();
    public void method() {
        myAbstractMethod();
    }
}

So i can't use the abstract class as a target for a lambda expressions and method references.

public class Lambdas {
    public static void main(String[] args) {
        MyFunctionalAbstractClass functionalAbstractClass = () -> {};
    }
}

The compilation error is: The target type of this expression must be a functional interface.

Why the language designers imposed this restriction ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
246 views
Welcome To Ask or Share your Answers For Others

1 Answer

This has been an important topic since the very inception of the Lambda project and has received a lot of thought. Brian Goetz, the chief Java Language architect, strongly supports the view of lambda as a function, not an object. Quote:

It is my belief that the best direction for evolving Java is to encourage a more functional style of programming. The role of Lambda is primarily to support the development and consumption of more functional-like libraries

I am optimistic about Java's future, but to move forward we sometimes have to let go of some comfortable ideas. Lambdas-are-functions opens doors. Lambdas-are-objects closes them. We prefer to see those doors left open.

Here is a link to the quote's source and here is Brian's more recent post which reiterates the same philosophical points and reaffirms them with additional, more practical arguments:

Making the model simpler opens doors to all sorts of VM optimizations. (Jettisoning identity is key here.) Functions are values. Modeling them as objects makes them heavier, and more complex, than they need to be.

Before throwing this use case under the bus, we did some corpus analysis to found how often abstract class SAMs are used compared to interface SAMs. We found that in that corpus, only 3% of the lambda candidate inner class instances had abstract classes as their target. And most of them were amenable to simple refactorings where you added a constructor/factory that accepted a lambda that was interface-targeted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...