In your code, the interface StringFunction
has only one method: run(String str)
. In Java, such interfaces are called functional interfaces, and they have a useful feature—lambda expressions.
When you write:
StringFunction exclaim = (s) -> s + "!";
Java understands that this is just a shorthand way to implement the run()
method because StringFunction
has no other methods.
If you were to write the code in a traditional way, it would look like this:
class ExclaimFunction implements StringFunction {
@Override
public String run(String str) {
return str + "!";
}
}
And you would have to use it like this:
StringFunction exclaim = new ExclaimFunction();
But why create unnecessary classes when you can do everything in one line?
Java automatically creates an anonymous class behind the scenes, which is why run() works even though you haven’t explicitly defined it anywhere. This is just a way to make the code shorter and more convenient.