I have several child classes extending an abstract parent class. I want the parent class to have a static ArrayList holding instances of each child. If possible, I would like to be able to add more child classes without having to change the parent class's code.
One solution I came up with is to give each of the child classes a static block that will add an instance of itself to the ArrayList. The only problem with this is that I then need to make some call to each child to get it to load and run the block.
abstract public class Parent {
protected static ArrayList<Parent> children = new ArrayList<Parent>();
}
public class ChildA extends Parent {
static {
children.add(new ChildA());
}
}
public class ChildB extends Parent {
static {
children.add(new ChildB());
}
}
Is there a way around this? Can I load a class without making a call to it? Would there be any better ways of doing this?
Edit: This is actually for a tile based game. I have an abstract "Tile" class and an arbitrary number of tile types extending it. I would like to be able to easily add new tiles to the game without having to change the code all over the place. If you have a better idea for how to do this, I am open to suggestion.
You can do it outside the class hierarchy. Have a utility function that uses reflection to find all descendants of Parent and then adds them to your list.