Array of Objects in Java

We can create an array of not only basic types(like int, double and char), but of objects as well. In this case the individual elements of the array store the reference to the objects.

You generally go through following three steps when dealing with an array of objects:

  1. Declare the array variable and allocate memory for array elements using new.
  2. Initialize each element with an Object using a constructor.
  3. If needed, set values of each array element using setters of the Objects.

An Example

In the example below, Animal is a class with one setter method setColor() and one getter method. We take all the three steps pointed above:

The output is:


Graphical Representation of the processes

Step 1: After this step:

  • Memory for the array has been allocated.
  • But each array member holds only null value as no objects have still been created.
Declaration and memory allocation for array of objeccts
After Declaration and memory allocation for array of objeccts

Step 2 : After this step:

  • Objects of Animal class have been created.
  • Array elements have been assigned the address of those Objects.
  • Array elements only contain default values. If no default value is specified then the value is undefined.
Declaration and memory allocation for array of objeccts
After initialization of each array member with objects of class Animal

Step 3 : After this step

  • Objects have been fully initialized by calling setter methods of the respective objects.
  • The array Animal is ready for further computation.
Declaration and memory allocation for array of objeccts
After the objects have been fully initialized