Task : To implement a call-back facility
Myclass m
creates a Timer t
t
to run in parallel
m
continues to run.Timer t
notifies Myclass m
when the timer ends.
Myclass m
has a function timerdone.
Myclass
:public class Myclass{
public void f(){
...
Timer t = new Timer(this); // Timer t should know who to notify. Myclass m passes its identity when it creates a Timer.
...
t.start();
...
}
public void timerdone() { ... }
}
Timer
public class Timer implements Runnable{
//Now timer can be invoked in parallel
private Myclass owner; //instance variable
public Timer(Myclass o){
owner = o;
}
public void start(){
...
owner.timerdone();
}
}
Here the Timer
is specific to Myclass
.
Timer
?To do this, make use of Java Class hierarchy.
Change Parameter of the Timer
constructor to type Object
→ Now compatible with any object that calls the timer.
Problem: Since we need to notify the calling object that the timer is done, we use timerdone()
function.
So we need to cast owner
back to Myclass
to call the timerdone()
function.
Solution : Use Interfaces.