85 lines
1.8 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// innerclasses/Callbacks.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
// Using inner classes for callbacks
2016-07-28 12:48:23 -06:00
// {java innerclasses.Callbacks}
2015-06-15 17:47:35 -07:00
package innerclasses;
interface Incrementable {
void increment();
}
// Very simple to just implement the interface:
class Callee1 implements Incrementable {
private int i = 0;
@Override
public void increment() {
i++;
2015-11-03 12:00:44 -08:00
System.out.println(i);
2015-06-15 17:47:35 -07:00
}
}
class MyIncrement {
2015-12-02 09:20:27 -08:00
public void increment() {
System.out.println("Other operation");
}
2015-06-15 17:47:35 -07:00
static void f(MyIncrement mi) { mi.increment(); }
}
// If your class must implement increment() in
// some other way, you must use an inner class:
class Callee2 extends MyIncrement {
private int i = 0;
@Override
public void increment() {
super.increment();
i++;
2015-11-03 12:00:44 -08:00
System.out.println(i);
2015-06-15 17:47:35 -07:00
}
private class Closure implements Incrementable {
@Override
public void increment() {
// Specify outer-class method, otherwise
2016-01-25 18:05:55 -08:00
// you'll get an infinite recursion:
2015-06-15 17:47:35 -07:00
Callee2.this.increment();
}
}
Incrementable getCallbackReference() {
return new Closure();
}
}
class Caller {
private Incrementable callbackReference;
2016-01-25 18:05:55 -08:00
Caller(Incrementable cbh) {
callbackReference = cbh;
}
2015-06-15 17:47:35 -07:00
void go() { callbackReference.increment(); }
}
public class Callbacks {
public static void main(String[] args) {
Callee1 c1 = new Callee1();
Callee2 c2 = new Callee2();
MyIncrement.f(c2);
Caller caller1 = new Caller(c1);
2016-01-25 18:05:55 -08:00
Caller caller2 =
new Caller(c2.getCallbackReference());
2015-06-15 17:47:35 -07:00
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Other operation
1
1
2
Other operation
2
Other operation
3
2015-09-07 11:44:36 -06:00
*/