class
Use inner class for callbacks
With this example we are going to demonstrate how to use inner class for callbacks to a class. The example is described in short:
- We have created an interface,
Incrementableand a class to implement it,Callee1. It has a methodincrement(), that increases an int value. - We have also created a class,
MyIncrementthat consists of a methodincrement()and astaticmethodf(MyIncrement mi)that gets aMyIncrementobject and calls itsincrement()method. - Another class is
Callee2that extendsMyIncrementand consists of a method,incr()and a private classClosurethat implements theIncrementableand overrides itsincrement()method, where it calls itsincr()method. It also has a methodgetCallBackReference()that returns a newClosureinstance. - We have another class,
Callerthat consists of anIncrementable, it has a constructor using theIncrementableand a methodgo()that calls theincrement()method ofIncrementable. - We create a new instance of
Callee1andCallee2. - When calling
f(MyIncrement mi)method ofMyIncrement, usingCallee1object as parameter it callsincrement()method ofMyIncreament. - When creating a new instance of
Caller, using theCallee1object in its constructor, it returns theCallee1object, so when itsgo()method is called , theCallee1object’s private int value is incremented and returned. - When creating a new instance of
Callerusing in its constructor a newClosurethat theCallee2object’sgetBackREference()returns, a newClosureobject is returned. So when callinggo()method, theClosureobject that is an inner class inCallee2increments the int i ofCallee2.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
interface Incrementable {
void increment();
}
// Very simple to just implement the interface:
class Callee1 implements Incrementable {
private int i = 0;
@Override
public void increment() {
i++;
System.out.println(i);
}
}
class MyIncrement {
void increment() {
System.out.println("Other operation");
}
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;
private void incr() {
i++;
System.out.println(i);
}
private class Closure implements Incrementable {
@Override
public void increment() {
incr();
}
}
Incrementable getCallbackReference() {
return new Closure();
}
}
class Caller {
private Incrementable callbackReference;
Caller(Incrementable cbh) {
callbackReference = cbh;
}
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);
Caller caller2 = new Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
}
Output:
Other operation
1
2
1
2
This was an example of how to use inner class for callbacks to a class in Java.

