Using inner classes for callbacks : Nested Classes « Class Definition « Java Tutorial






interface InterfaceA {
  void increment();
}

class ClassA implements InterfaceA {
  private int i = 0;

  public void increment() {
    i++;
    System.out.println(i);
  }
}

class ClassB {
  void increment() {
    System.out.println("Other operation");
  }

  static void f(ClassB mi) {
    mi.increment();
  }
}

class ClassC extends ClassB {
  private int i = 0;

  private void incr() {
    i++;
    System.out.println(i);
  }

  private class Closure implements InterfaceA {
    public void increment() {
      incr();
    }
  }

  InterfaceA getCallbackReference() {
    return new Closure();
  }
}

class Caller {
  private InterfaceA callbackReference;

  Caller(InterfaceA cbh) {
    callbackReference = cbh;
  }

  void go() {
    callbackReference.increment();
  }
}

public class MainClass {
  public static void main(String[] args) {
    ClassA c1 = new ClassA();
    ClassC c2 = new ClassC();
    ClassB.f(c2);
    Caller caller1 = new Caller(c1);
    Caller caller2 = new Caller(c2.getCallbackReference());
    caller1.go();
    caller1.go();
    caller2.go();
    caller2.go();
  }
}








5.14.Nested Classes
5.14.1.Creating instances of inner classes
5.14.2.Nested Classes
5.14.3.Creating a new nested object outside
5.14.4.Static Nested Classes
5.14.5.Creating inner classes
5.14.6.Defining references to inner classes
5.14.7.Nesting a class within a method
5.14.8.Nesting a class within a scope.
5.14.9.Nested classes (static inner classes)
5.14.10.An inner class cannot be overriden like a method
5.14.11.Two ways that a class can implement multiple interfaces
5.14.12.Nested classes can access all members of all levels of the classes they are nested within
5.14.13.Proper inheritance of an inner class.
5.14.14.Using inner classes for callbacks
5.14.15.Returning a reference to an inner class
5.14.16.Putting test code in a nested class
5.14.17.With concrete or abstract classes, inner classes are the only way to produce the effect of multiple implementation inheritance.
5.14.18.Local inner class can have a constructor