Write a java program to create an array of objects.
Creating the array of objects is similar to creating an array of any primitives types.
Example:
1 2 3 4 5 | //Array of Integers int numbers[] = new int[size]; //Array of Objects class_name object_name[] = new class_name[size]; |
It is because the class is a User-Defined data type, therefore it can be used as a type to create an array and the array created using the class as its type, is the array of objects.
Let’s see an example in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import java.util.Scanner; class Student{ public int roll; public String name; Student(int roll, String name){ this.roll = roll; this.name = name; } //Override toString() to print object directly public String toString(){ return "{roll: "+this.roll+", name: "+this.name+"}"; } } class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); //Declare Array of class Students Student stdArray[]= new Student[3]; System.out.println("Enter 3 students details"); for(int i=0; i<3; i++){ //Create a new object of class Student Student newStudent = new Student(in.nextInt(),in.next()); //Assign the object to the object array stdArray[i] = newStudent; } System.out.println("Students details are:"); for(int i=0; i<3; i++){ //Student.toString() method will be used to output object System.out.println(stdArray[i]); } } } |
Output
1 2 3 4 5 6 7 8 | Enter 3 students details 1 Ak 2 AAk 3 Avk Students details are: {roll: 1, name: Ak} {roll: 2, name: AAk} {roll: 3, name: Avk} |
In the above program, we have overridden the toString() method in the class so that we can output its object directly. Whatever we return as a string from the overridden toString() method will be printed for respective instance of the class.
Hope now you can easily create an array of objects in Java. If you have any doubts or suggestion then comment below.