I am new to OOP, and I’m trying to make a simple game to help me learn Java. My idea was to make an enemy class, but I want the amount of enemies to be dynamic. I tried making a new object as an array rather than manually typing attker1 attker2 and so on …
Mole attacker[3];
attacker[0] = new Mole();
attacker[1] = new Mole();
attacker[2] = new Mole();
I hope you get the idea of what I’m trying to do. I’ve tried searching Google, but I keep getting tutorials on how to make arrays out of regular data types (i.e. int, char, etc.). I’d like to know what it’s called, whatever I’m trying to do. If there is a better way of doing this I’ll listen to that too.
Thank you.
Arrays of objects are perfectly fine (indeed, often used more than simple arrays of primitive data types).
So, if you want the amount of enemies to be dynamic, you might want to use a Container class- specifically a resizable array. Look into classes Vector, ArrayList, etc.
Also note (I saw the Android tag) that creating new objects in the drawing loop can cause the Garbage Collector to be called and slow down the framerate while it works – be warned.
A variation on what you have: