1

Is it possible to write a Java interface from which you could create an anonymous class, but for which you can't create a lambda expression?

Why or why not???

  • Related - [Java8 Lambdas vs Anonymous classes](https://stackoverflow.com/questions/22637900/java8-lambdas-vs-anonymous-classes) – Naman Apr 23 '20 at 01:37

1 Answers1

4

Lambda expressions can only be used to implement functional interfaces, i.e. interfaces with exactly one abstract method.

JLS 15.27. Lambda Expressions says:

Evaluation of a lambda expression produces an instance of a functional interface (§9.8).

JLS 9.8. Functional Interfaces says:

A functional interface is an interface that has just one abstract method (aside from the methods of Object), and thus represents a single function contract.

So if you want a Java interface for which you can't create a lambda expression, make the interface have 2 or more abstract methods.

Anonymous classes can still implement such an interface, because they support implementation of more than one method.

Andreas
  • 154,647
  • 11
  • 152
  • 247