Frequently in a program, we want to work with a group of objects of the same type, such as fish in an aquarium. A very basic way to do this is to have a group of variables.
AquaFish fish1 = new AquaFish(fishtank); AquaFish fish2 = new AquaFish(fishtank); AquaFish fish3 = new AquaFish(fishtank); AquaFish fish4 = new AquaFish(fishtank); AquaFish fish5 = new AquaFish(fishtank); // Move each fish forward 10 times, without changing direction. for ( int i = 0; i < 10; i++ ) { fish1.moveForward(); fish2.moveForward(); fish3.moveForward(); fish4.moveForward(); fish5.moveForward(); }This approach has several problems:
- It would quickly get tedious as the number of items grows.
- It's easy to make mistakes when repeatedly copying code and then customizing it for each item.
- The number of items has to be known, definitely, when writing the program. This means that to change the number of items, you have to change and re-compile the program. It's not possible to make the number depend on information known only when the program runs (for example, you could not let the user enter how many items to include).