Java Reference
In-Depth Information
int
int recompute ( int
int x );
the interface would cease to be functional, but the compiler or IDE would detect that fact as
soon as you saved or compiled the interface, saving you from puzzling out why the lambda
expression was invalid. Javac will complain as follows:
C:\javasrc>javac -d build src/lang/MyFunctionalInterface.java
src\lang\MyFunctionalInterface.java:3: error: Unexpected @FunctionalInterface
annotation
@FunctionalInterface
^
MyFunctionalInterface is not a functional interface
multiple non-overriding abstract methods found in
interface MyFunctionalInterface
1 error
C:\javasrc>
Sometimes, of course, you really do need an interface to have more than one method. In that
case, the illusion (or the effect) of functionality can sometimes be preserved by denoting all
but one of the methods with the “default” keyword—the nondefault method will still be us-
able in lambdas. A default method has a method body:
public
public interface
interface ThisIsStillFunctional
ThisIsStillFunctional {
default
default int
int compute ( int
int ix ) { return
return ix * ix + 1 };
int
int anotherMethod ( int
int y );
}
Only default methods may contain executable statements, and there may only be one
nondefault method per functional interface.
Oh, and of course, our MyFunctionalInterface given earlier can be totally replaced by
java.util.function.IntUnaryOperator , changing the method name apply() to ap-
plyAsInt() . There is a version of the ProcessInts program under the name ProcessInt-
sIntUnaryOperator in the javasrc repository.
Search WWH ::




Custom Search