Array of Objects

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

Car[] model = new Car[5];

The above statement creates the array which can has length of five objects. It doesn’t create the objects themselves. They have to be created separately, in the following complete example.

Example

class Car {
	int gears;
}

public class ObjectsExample {
	public static void main(String[] args) {

		Car[] model = new Car[5]; // 5 is length of array

		for (int a = 0; a < 5; a++) {
			model[a] = new Car(); // allocating memory to arrays one by one
			model[a].gears = a + 1; // assigning values
		}

		// Printing array elements
		for (int a = 0; a < 5; a++) {
			System.out.print("Object = model[" + a + "]");
			System.out.println(" Gears = " + model[a].gears);
		}
	}
}

Output

Object = model[0] Gears = 1
Object = model[1] Gears = 2
Object = model[2] Gears = 3
Object = model[3] Gears = 4
Object = model[4] Gears = 5
Share

You may also like...