Learn how to create an array of objects in java with example code – An array of user defined class objects can also be created the same way as we create array of built-in type.
For example, here is an array for 5 int type.
int [] numbers = new int[5];
Similarly, an Array of 5 objects of the class Car can be created as below.
Car[] obj = new Car[5];
In an array of objects, all the objects will be of same class. [ Recommend to read how to create an object of a class in java]
We have created array for 5 Car objects in which we can store 5 objects of Car class.
Now for each 0 to 4 slot, we can create Car object as below.
obj[0] = new Car();
obj[1] = new Car();
obj[2] = new Car();
obj[3] = new Car();
obj[4] = new Car();
Array of objects java example
This program creates an array of 5 objects of class Car. Set the name of each car. Using for loop, it will retrieve each array elements and display the names of the cars on console.
/*
* Array of objects in java example program
*/
class Car {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/*
* Test array of objects
*/
public class Sample {
public static void main(String[] args) {
// Create an array of 5 student objects.
Car[] obj = new Car[5];
// Create first car object
obj[0] = new Car();
// Set car names
obj[0].setName("Maruti");
obj[1] = new Car();
obj[1].setName("Honda");
obj[2] = new Car();
obj[2].setName("Ford");
obj[3] = new Car();
obj[3].setName("Hundai");
obj[4] = new Car();
obj[4].setName("Nissan");
// Display all cars
for (int i = 0; i < 5; ++i) {
System.out.println("Car : " + obj[i].getName());
}
}
}
Output:
Car : Maruti
Car : Honda
Car : Ford
Car : Hundai
Car : Nissan