I have an abstract class that has an array of abstract things:
Abstract Color has abstract ColorThings[]
I have several concrete classes that each have an array of concrete things:
Concrete RedColor has concrete RedThings[]
Concrete BlueColor has concrete BlueThings[]
All are related:
RedColor and BlueColor are Colors.
RedThings[] and BlueThings[] are ColorThings[].
What design pattern do I need here? I already have a factory method going on, where any Color sub-class must be able to generate an appropriate ColorThing. However, I'd also like to be able to have this method in Color, which sub-classes would not need to implement:
addColorThing(ColorThing thing) {/*ColorThing[] gets RedThing or BlueThing*/}
Additionally, I'd like each sub-class to be able to instantiate the super.ColorThings[] as their own version of the array:
class RedColor {
colorThings[] = new RedThings[];
}
Does Java allow for any of this? Can I redesign any of it better?
Generics will let you do what you want:
The idea here is that each subclass of
Color
needs to declare what specific subclass ofColorThings
they use. By using the type parameterT
, you can achieve this.Read more in the docs...