I may have the wrong idea with this but bear with me…
I have a function that I want to call with one of multiple sub-class types ComboA, ComboB, etc (all extending the superclass “Combos”).
ArrayList<Combos> combos = null; //of type combos, which is super class of Combo A and Combo B
switch (which) {
case 1:
combos = CombosA; //this is of type ComboA
break;
case 2:
combos = CombosB; //this is of type ComboB
break;
}
Depending on the switch statement, I want a single variable in the function (combos) to retain all the class functions of the sub-class. This is so I don’t have to make a bunch of functions for each Combo type -I’d like to use the same variable name (combos) regardless of which subclass it is.
I tried using generics, but the thing is, the CombosA and CombosB variables are defined outside of this scope, global to the class, and I don’t know how to use generics unless I define the function as
public <E extends Combos> void Test(ArrayList <E> CombosA)
Or something like this, which I guess would require another separate variable to be sent in the function call that wasn’t global. I might be able to copy the CombosA array list and send the copy into the function to get the generic function to work but, I thought there must be a better way.
Any help would be greatly appreciated!
It depends on what you next want to do with the selected “
combo“. SinceComboAandComboBare subclasses ofCombosideally you would just call a “Combos” method to perform a common action on each combo. Each subclass can then perform it’s own implementation of the function.For example, if you are going to do some sort of update on
ComboAorComboBetc, then there could be anupdate()method (possibly abstract) in theCombosclass.ComboAhas its version ofupdate()andComboBhas its version ofupdate(). Your loop then just loops over the combos calling theupdate()method knowing that each will do the correct thing without having to specify type.Does that help?