3.1 Lesson Outcomes
After completing this lesson, learners will be able to:
- Create classes for object arrays.
- Declare arrays of objects.
- Initialize objects inside arrays.
- Access object attributes and methods.
- Iterate through arrays of objects.
3.2 Overview
An array of objects stores multiple objects of the same class in a single array structure. Arrays of objects are commonly used in Java applications to manage collections of related information such as:
- students,
- books,
- employees,
- and products.
This lesson introduces learners to the practical creation and use of arrays of objects in Java programming.
Arrays of objects are important in:
- object-oriented programming,
- data management,
- software applications,
- and enterprise systems.
Understanding arrays of objects is important because they are widely used in real-world software development.
PA0501 — Create an Array of Objects
Arrays of objects are created using class references.
Example Class
Java
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(name + ” ” + age);
}
}
Declaring an Array of Objects
Java
Student[] students = new Student[3];
Initializing Objects in the Array
Java
students[0] = new Student(“Thabo”, 20);
students[1] = new Student(“Lerato”, 22);
students[2] = new Student(“Sipho”, 21);
Iterating Through the Object Array
Java
for (Student s : students) {
s.display();
}
Complete Example Program
Java
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(“Name: ” + name + “, Age: ” + age);
}
}
public class StudentArrayExample {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student(“Thabo”, 20);
students[1] = new Student(“Lerato”, 22);
students[2] = new Student(“Sipho”, 21);
for (Student s : students) {
s.display();
}
}
}
Importance of Arrays of Objects
Arrays of objects support:
- structured data storage,
- object-oriented programming,
- and management of multiple records.
3.5 Key Notes / Summary
- Arrays of objects store multiple objects of the same class.
- Objects are created using constructors.
- Arrays of objects use references.
- Object arrays can be iterated using loops.
- Methods can be called on objects inside arrays.
- Arrays of objects are widely used in software development.