samedi 12 février 2022

Why does this Java callback pattern work?

I came across this Java callback example on the internet, and I don't understand why it works.

Callback.java:

interface Callback {
  void call();
}

SomeTask.java:

class SomeTask extends Thread {
  @Override
  public void run() {
    System.out.println("SomeTask started");
  }

  public void execute(Callback callback) {
    System.out.println("execute in SomeTask");

    callback.call();
  }
}

SomeThread.java:

class SomeThread extends Thread {
  @Override
  public void run() {
    System.out.println("SomeThread started");

    SomeTask someTask = new SomeTask();

    someTask.start();

    someTask.execute(this::foo);
  }

  private void foo() {
    System.out.println("foo in SomeThread");
  }
}

Main.java:

class Main {
  public static void main(String[] args) {
    new SomeThread().start();
  }
}

Specifically, why does "someTask.execute(this::foo)" work when SomeThread does not implement the Callback interface, and SomeTask invokes "callback.call()"?

And, is the the correct way to implement a callback pattern in Java?

Aucun commentaire:

Enregistrer un commentaire