How to dynamically override a method in an object
Posted
by
Ace Takwas
on Programmers
See other posts from Programmers
or by Ace Takwas
Published on 2013-10-26T08:03:12Z
Indexed on
2013/10/26
10:11 UTC
Read the original article
Hit count: 200
java
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?
© Programmers or respective owner