How to dynamically override a method in an object
- by Ace Takwas
If this is possible, how can I change what a method does after I might have created an instance of that class and wish to keep the reference to that object but override a public method in it's class' definition?
Here's my code:
package time_applet;
public class TimerGroup implements Runnable{
private Timer hour, min, sec;
private Thread hourThread, minThread, secThread;
public TimerGroup(){
hour = new HourTimer();
min = new MinuteTimer();
sec = new SecondTimer();
}
public void run(){
hourThread.start();
minThread.start();
secThread.start();
}
/*Please pay close attention to this method*/
private Timer activateHourTimer(int start_time){
hour = new HourTimer(start_time){
public void run(){
while (true){
if(min.changed)//min.getTime() == 0)
changeTime();
}
}
};
hourThread = new Thread(hour);
return hour;
}
private Timer activateMinuteTimer(int start_time){
min = new MinuteTimer(start_time){
public void run(){
while (true){
if(sec.changed)//sec.getTime() == 0)
changeTime();
}
}
};
minThread = new Thread(min);
return min;
}
private Timer activateSecondTimer(int start_time){
sec = new SecondTimer(start_time);
secThread = new Thread(sec);
return sec;
}
public Timer addTimer(Timer timer){
if (timer instanceof HourTimer){
hour = timer;
return activateHourTimer(timer.getTime());
}
else if (timer instanceof MinuteTimer){
min = timer;
return activateMinuteTimer(timer.getTime());
}
else{
sec = timer;
return activateSecondTimer(timer.getTime());
}
}
}
So for example in the method activateHourTimer(), I would like to override the run() method of the hour object without having to create a new object. How do I go about that?