I have one Worker interface with one method:
interface Worker {
public void work()
}
I have 2 classes that implements Worker,
class RoadWorker implements Worker {
public void setPropertyA() {}
public void work() {}
}
another one,
class GardenWorker implements Worker {
public void setPropertyB() {}
public void work() {}
}
In my Application class - based on some input flag - I want to instantiate one specific type of worker...
class Application {
// flag
String whichWorker = "Road";
// instantiate
if (whichWorker == "Road") {
RoadWorker worker = new RoadWorker();
worker.setPropertyA();
} else {
GardenWorker worker = new GardenWorker();
worker.setPropertyB();
}
// use
worker.work(); <----- OF COURSE THIS DOES NOT WORK (no reference)
So, I tried this -
class Application {
// flag
String whichWorker = "Road";
Worker worker;
// instantiate
if (whichWorker == "Road") {
worker = new RoadWorker();
worker.setPropertyA(); <----- DOES NOT WORK
} else {
worker = new GardenWorker();
worker.setPropertyB(); <----- DOES NOT WORK
}
// use
worker.work();
My question is - how do I design my program to achieve this requirement? I know one crude option is to define worker as Object but then I will have to do lots of lots of type casting that I don't want. Can anyone please suggest?