Advertisement
aikikode

Java callback example

May 9th, 2012
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. interface Callable
  2. {
  3.     public void callBackMethod();
  4. }
  5.  
  6. class Worker
  7. {
  8.     // Worker gets a handle to the boss object via the Callable interface.
  9.     // There's no way this worker class can call any other method other than
  10.     // the one in Callable.
  11.     public void doSomeWork(Callable myBoss)
  12.     {
  13.         myBoss.callBackMethod();
  14.         // ERROR!
  15.         //myBoss.directMethod();
  16.     }
  17. }
  18.  
  19. class Boss implements Callable
  20. {
  21.     public Boss()
  22.     {
  23.         // Boss creates a worker object, and tells it to do some work.
  24.         Worker w1 = new Worker();
  25.         // Notice, we're passing a reference of the boss to the worker.
  26.         w1.doSomeWork(this);
  27.     }
  28.     public void callBackMethod()
  29.     {
  30.         System.out.println("What do you want?");
  31.     }
  32.     public void directMethod()
  33.     {
  34.         System.out.println("I'm out for coffee.");
  35.     }
  36. }
  37.  
  38. public class CallBack
  39. {
  40.     // Main driver.
  41.     public static void main(String[] args)
  42.     {
  43.         Boss b = new Boss();
  44.         b.directMethod();
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement