javainterface

Java example: Why can a function in this w3schools example run when it is not defined?


Here is the issue, you can find it in w3schools lamda expressions chapter last example:

interface StringFunction {
  String run(String str);
}

And:

public class Main {
  public static void main(String[] args) {
    StringFunction exclaim = (s) -> s + "!";
    StringFunction ask = (s) -> s + "?";
    printFormatted("Hello", exclaim);
    printFormatted("Hello", ask);
  }
  public static void printFormatted(String str, StringFunction format) {
    String result = format.run(str);
    System.out.println(result);
  }
}

So from my understanding,the code here doesnt explicitly define the function '.run()' in the interface 'StringFunction', only the parameters is stated in it.

And I believe one needs to implement this class by making another class to further define the behaviour of this function. Therefore the major confusion here is that '.run()' can for some reason work without any defintition, so if it is not a built-in function of java please someone explain to me as to why and how is this possible. The fact that 'StringFunction' can be used as a class for 'exclaim' and 'ask' is also very confusing without any definition.

I just started out with java so I hope for your understanding.


Solution

  • Functional interface

    StringFunction is a functional interface. In other words it is an interface with a single abstract method.
    An abstract method is a method without definition (without body).

    Such interfaces can be implemented using a lambda expression. As it is done in your example.

    So StringFunction exclaim = (s) -> s + "!" is an implementation of StringFunction and an instance of that implementation.

    You can think of StringFunction exclaim = (s) -> s + "!" as a short version of following:

    class ExclamationAppender implements StringFunction {
        @Override
        public String run(String s) {
            return s + "!";
        }
    }
    
    StringFunction exclaim = new ExclamationAppender();