![]() | Session 3 | ![]() |
An array of objects
In the previous sections, we have declared and created single objects (e.g. dog Liza and dog Marfa). However, we can create an array whose elements are objects of the same data type:
Dog[] pet_shop = new Dog[20];
Variable pet_shop contains references to the instances. But at the moment, all instances have the value of null. Try to print any of the array elements, e.g.:
System.out.println(pet_shop[8]);
Next, add our dog Liza to pet_shop:
pet_shop[8] = liza;
Now try to output pet_shop[8].
We can create several dogs using a loop:
String breed = "labrador";
String size = "small";
String color = "brown";
for (int i = 0; i < pet_shop.length; i++) {
pet_shop[i] = new Dog("L" + (i + 1),breed,i+1,size,color);
}
System.out.println("The dog number 10 in pet shop: " + pet_shop[9] + ".");
![]() | Session 3 | ![]() |

