Within my program I have these classes:
public class Zombie extends Monster
{
public static String getType() {return "Zombie";}
}
public class Skeleton extends Monster
{
public static String getType() {return "Skeleton";}
}
Somewhere in my program I want to maintain an List of all Monsters that exist in the program which currently I do like this:
public class MonsterLister
{
//ArrayList to hold the monsters
private static ArrayList<String> monsters = new ArrayList<>();
public static void main(String[] args)
{
MonsterLister.add(Zombie.getType());
MonsterLister.add(Skeleton.getType());
//More code
}
public static void addMonster(String monster)
{
monsters.add(monster);
}
public static ArrayList<String> getMonsters()
{
return monsters;
}
}
Further down the development road I will want to add more monsters which might look like this:
public class Spider extends Monster
{
public static String getType() {return "Spider";}
}
Now i would go and add this to the main method, but I would like a way for the program to automatically populate the monster list. So instead of having to go to the main method every time I add a new monster and adding a method call for it I want the program to just use all available classes. Furthermore the list of methods in my main method seems somewhat sloppy.
I thought about having an eventListener in every monster class but I would still need to call the class to register the eventListener so I would still have to call every class separately. A static constructor in every class would also only trigger once a method inside the class is called.
Is this possible in Java?
Note: the code example above is not my actual program, but instead of trying to make the actual program understandable with only a few code pieces, I decided to come up with a different example!