If I got the question right, you want to implement a class whose behavior changes dynamically, depending on the situation. You can implement one of the common patterns (sorry, don't remember its name):
//create function objects
class Sum implements HasBarMethod{
public double bar(double x) {
return x+x;
}
}
class Multiply implements HasBarMethod{
public double bar(double x) {
return x*x;
}
}
//create the base class
class DynamicBehavior{
private HasBarMethod strategy;
//other class fields
public DynamicBehavior(HasBarMethod strategy){
this.strategy = strategy;
// ...
}
public double bar(double x) {
return strategy.bar(x);
}
//you may want to handle strategy change in a different way.
//this here is just a simple example.
public setStrategy(HasBarMethod strategy){
this.strategy = strategy;
}
//any code implementing strategy changes or whatever
}
This will allow you to change the strategies your class uses depending on its state or any other conditions you may wish to take into consideration.
An example of its usage:
public static void main(String args[]){
HasBarMethod defaultStrategy = new Sum();
DynamicBehavior dyn = new DynamicBehavior(defaultStrategy);
if( /*condition*/ ){
dyn.setStrategy(new Multiply());
}
double result = dyn.bar(5);
}
You might as well want to turn your strategy function objects into static fields of the base class as this will save you some memory and time by avoiding creation of their new instances each time you decide to switch strategies.