When the expression is assigned to the myNum variable, a class instance is created in which the lambda expression overrides the getValue () method of the MyNumber interface and defines its implementation.
No, that's not correct. A lambda is a "piece of code" that the compiler references as needed. That is one of the major advantages in terms of efficiency, the JVM doesn't have to create and load classes when executing the program.
You should test your example before posting the question since it is incorrect. The MyNumber interface is not functioning as a data type but rather as a method definition. It should be:
interface MyNumberSupplier {
double getValue();
}
MyNumberSupplier numberSupplier = () -> 123.45;
double d1 = numberSupplier.getValue();
Here you can see that the lambda expression is a piece of code that returns the value used to set d1. In this case the code returns the literal value 123.45 and when needed to set d1 the compiler just references that code in place of the numberSupplier.getValue(); line. You could expand the example to use more complicated code:
MyNumberSupplier getLess100 = () -> Math.random() * 100.0;
MyNumberSupplier getMore100 = () -> Math.random() * 100.0 + 100.0;
double d1;
if ( Math.random() < 0.5)
d1 = getLess100.getValue();
else
d1 = getMore100.getValue();
Here interface has been implemented two different ways but no classes (other than the MyNumberSupplier interface) have been defined, only pieces of code that are referenced as needed. A @FunctionalInterface can only have one method since a lambda expression can only be one piece of code.
Finally, you should note that there are many predefined interfaces in the java.util.function package included in java 8. For example java.util.function.Supplier<T>. Your code can then be written as:
Supplier<Double> myNumber= () -> 123.45;
double d1 = myNumber.get();