I want to make a piece of code which will store a class reference and is able to call a particular function inside of it. This would mean I can swap out the class to achieve different functionality. So for instance, I can have a class instance hold
classDelegate cl = new ofSomeClass();
cl.executeFunction("functionName");
In other words, I can initialize one class which calculates 1+1 and then another which calculates 2+2. This way I can dynamically swap out the calculation, simply passing a different class to inialize cl with.
This is a pain to explain… hopefully I made some sense… is this at all possible?
The question you posted is somewhat vague, but it sounds like you need to define an interface and then have each of the differen classes implement that interface. In your example, where you’re referencing a “calculate” method, you would just define an interface like this:
Then when you create your different classes, they would implement the interface like this:
Then in your code when you want to invoke the Calculate method you can cast an instance of the TwoPlusTwoCalculator, or OnePlusOneCalculator, or any other class that implements the interface as that interface:
public void GetValue ( int numOne, int numTwo )
{ TwoPlusTwoCalculator calculator = new TwoPlusTwoCalculator ( numOne, numTwo );
PerformCalculation ( calculator as ICalculator );
}
Is that what you’re trying to accomplish?