I was reading this tutorial on Java 8 where the writer showed the code:
interface Formula {
double calculate(int a);
default double sqrt(int a) {
Lambda expressions work in a completely different way from anonymous classes in that this
represents the same thing that it would in the scope surrounding the expression.
For example, this compiles
class Main {
public static void main(String[] args) {
new Main().foo();
}
void foo() {
System.out.println(this);
Runnable r = () -> {
System.out.println(this);
};
r.run();
}
}
and it prints something like
Main@f6f4d33
Main@f6f4d33
In other words this
is a Main
, rather than the object created by the lambda expression.
So you cannot use sqrt
in your lambda expression because the type of the this
reference is not Formula
, or a subtype, and it does not have a sqrt
method.
Formula
is a functional interface though, and the code
Formula f = a -> a;
compiles and runs for me without any problem.
Although you cannot use a lambda expression for this, you can do it using an anonymous class, like this:
Formula f = new Formula() {
@Override
public double calculate(int a) {
return sqrt(a * 100);
}
};