![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Array of objects is the collection of objects of the same class.
Normally we declare the multiple objects of a class just like normal variables as
Student s1,s2,s3 ....sn;
Before going to learn array of objects first learn about the array in java
classname arrayName[] = new classname[dimension];
classname : is the name of class which is defined
dimension : is the size of array starting from index 0 to n
Creating the array of 5 Objects of Student class as
Student s1[] = new Student[5];
This will create array of 5 objects of student class.
We need to allocate memory for every object as
Student s1[0] = new Student(); Student s1[1] = new Student(); Student s1[2] = new Student(); Student s1[3] = new Student(); Student s1[4] = new Student();
This can be done by using loops as below
for(int i=0;i<5;i++) { s1[i] = new Student(); }
Define a class Student having data members rollnumber,name,marks. accept and display detailes of 5 students.
import java.util.Scanner; class Student { Scanner sc; String name; int rollno; float marks; void getData() { sc = new Scanner(System.in); System.out.print("Enter name : "); name = sc.next(); System.out.print("Enter roll no : "); rollno = sc.nextInt(); System.out.print("Enter marks : "); marks = sc.nextFloat(); } void display() { System.out.println("\nName : "+name); System.out.println("Roll no: "+rollno); System.out.println("Marks : "+marks); } public static void main(String args[]) { int i; Student s1[] = new Student[5]; for(i=0;i<2;i++) { s1[i] = new Student(); s1[i].getData(); } System.out.println("\nStudent detailes are"); for(i=0;i<2;i++) s1[i].display(); } }
Output