fork download
  1. package chapter10;
  2.  
  3. interface Incrementable {
  4. void increment();
  5. }
  6.  
  7. class Callee1 implements Incrementable {
  8. private int i = 0;
  9.  
  10. public void increment() {
  11. i++;
  12. System.out.println(i);
  13. }
  14. }
  15.  
  16. class MyIncrement {
  17. public void increment() {
  18. System.out.println("Other operation");
  19. }
  20.  
  21. static void f(MyIncrement mi) {
  22. mi.increment();
  23. }
  24. }
  25.  
  26. class Callee2 extends MyIncrement {
  27. private int i = 0;
  28.  
  29. public void increment() {
  30. super.increment();
  31. i++;
  32. System.out.println(i);
  33. }
  34.  
  35. private class Closure implements Incrementable {
  36. public void increment() {
  37. Callee2.this.increment();
  38. }
  39. }
  40.  
  41. Incrementable getCallbackReference() {
  42. return new Closure();
  43. }
  44. }
  45.  
  46. class Caller {
  47. private Incrementable callbackReference;
  48.  
  49. Caller(Incrementable cbh) {
  50. callbackReference = cbh;
  51. }
  52.  
  53. void go() {
  54. callbackReference.increment();
  55. }
  56. }
  57.  
  58. public class CallBacks {
  59.  
  60. public static void main(String[] args) {
  61. Callee1 c1 = new Callee1();
  62. Callee2 c2 = new Callee2();
  63. MyIncrement.f(c2);
  64. Caller caller1 = new Caller(c1);
  65. Caller caller2 = new Caller(c2.getCallbackReference());
  66. caller1.go();
  67. caller1.go();
  68. caller2.go();
  69. caller2.go();
  70. }
  71. }
  72.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:58: error: class CallBacks is public, should be declared in a file named CallBacks.java
public class CallBacks {
       ^
1 error
stdout
Standard output is empty