Instead of doing this:
PersonInstance instance1 = new PersonInstance();
PersonInstance instance2 = new PersonInstance();
...
...
...
PersonInstance instance99 = new PersonInstance();
You could use an array
to create all 70 instances of PersonInstance, like:
PersonInstance[] personInstances = new PersonInstance[N];
for(int i = 0; i < personInstances.length; i++){
personInstances[i] = new personInstances();
}
Where N
is the number of slots in the array where you could store instances of PersonInstance
. In your case, N
would be 70:
PersonInstance[] personInstances = new PersonInstance[70];
for(int i = 0; i < personInstances.length; i++){
personInstances[i] = new personInstances();
}
Then if you would like to access PersonInstance number k
, you would do so by:
PersonInstace thisPerson = personInstances[k-1];
since an array start from index 0, e.g if you want to access PersonInstance 56
, you would do so by:
PersonInstace thisPerson = personInstances[55];
Hope it helps.
UPDATED ANSWER:
If for example, BrotherInstance extends PersonInstance, you could add a BrotherInstance to your PersonInstance array like:
PersonInstance[] personInstances = new PersonInstance[70];
//add 50 PersonInstances
for(int i = 0; i < personInstances.length-20; i++){
personInstances[i] = new PersonInstances();
}
//add 20 BrotherInstances
for(int i = 50; i < personInstances.length; i++){
personInstances[i] = new BrotherInstances();
}
And access them one by one like:
PersonInstance currentPerson = personInstances[24] //A PersonInstance
PersonInstance currentBrother = personInstances[61] //A Brother instance
or
BrotherInstance currentBrother = personInstances[61] //A Brother instance
or loop them all like:
for(PersonInstance person: personInstances){
//Do something with every person here, maybe print out something.
}
That for-loop
will loop through all PersonInstances, wether they are PersonInstance or BrotherInstance since they are either a PersonIntance or extend PersonInstance.