[Solved] How to create array of object references in Java?


Arrays are used to store primitive values and objects. For example, we can create an array of String or any class objects.
To explain, Lets create a class Employee containing a single instance variable empId. Following is the definition of this class.

class Employee{
   int empId;
}

An array of objects is created just like an array of primitive type data items in the following way.

Employee[] EmployeeArray = new Employee[10];

The above statement creates the array which can hold references to ten Employee objects. It doesn’t create the Employee objects themselves.
They have to be created separately using the constructor of the Employee class. The EmployeeArray contains ten memory spaces in which the
address of ten Employee objects may be stored. If we try to access the Employee objects even before creating them, run time errors would occur.

The Employee objects have to be instantiated using the constructor of the Employee class and their references should be assigned to the array elements in the following way.

EmployeeArray[0] = new Employee();

In this way, we create the other Employee objects also. If each of the Employee objects have to be created using a different constructor, we use a statement similar to the above several times. However, in this particular case, we may use a for loop since all Employee objects are created with the same default constructor.

for ( int i=0; i<EmployeeArray.length; i++) {
EmployeeArray[i]=new Employee();
}

The above for loop creates ten Employee objects and assigns their reference to the array elements.

solved How to create array of object references in Java?