Ch. 2. Object Oriented Concepts.

2.3 Array of Objects

Introduction

Just as arrays can store collections of primitive data types (e.g., integers, floats, characters), they can also store collections of objects. An array of objects is an array where each element is a reference to an object of a particular class. This allows you to group multiple instances of the same class under one name, simplifying management and processing.

Explanation

When you declare an array of a primitive type, such as:

int[] numbers = new int[5];

memory is allocated for five integers.

However, when you declare an array of objects, such as:

Car[] cars = new Car[5];

you are not immediately creating Car objects. Instead, you are creating an array that can hold references to Car objects. Initially, each element is set to null.

To store actual objects:

1.     Declare the array of object references.

2.     Instantiate each object individually using the new keyword.

Think of it like a parking lot:

  • Declaring Car[] parkingSpots = new Car[5]; is like creating 5 empty parking spots.
  • Instantiating cars for each spot is like parking the cars there:

·         parkingSpots[0] = new Car();

·         parkingSpots[1] = new Car();

 

Syntax

// Declaring and instantiating an array of object references

ClassName[] arrayName = new ClassName[size];

 

// Instantiating objects and assigning them to the array

arrayName[0] = new ClassName();

arrayName[1] = new ClassName();

// … and so on

Accessing Members of Objects:

arrayName[index].fieldName;

arrayName[index].methodName();

 

Example 1: Array of Dog Objects

Suppose we have a Dog class:

 // File: Dog.java

public class Dog {

    // Fields

    String name;

    String breed;

 

    // Constructor

    public Dog(String name, String breed) {

        this.name = name;

        this.breed = breed;

    }

 

    // Method for barking

    public void bark() {

        System.out.println(name + " says: Woof! Woof!");

    }

 

    // Method to display dog information

    public void displayInfo() {

        System.out.println("Name: " + name + ", Breed: " + breed);

    }

}

And now, create an array of Dog objects:

 // File: Kennel.java

public class Kennel {

    public static void main(String[] args) {

        // 1. Declare an array for 3 Dog objects

        Dog[] kennelDogs = new Dog[3];

 

        // 2. Instantiate Dog objects and assign them to the array

        kennelDogs[0] = new Dog("Buddy", "Golden Retriever");

        kennelDogs[1] = new Dog("Lucy", "Labrador");

        kennelDogs[2] = new Dog("Max", "German Shepherd");

 

        // Display all dogs in the kennel

        System.out.println("\n— Listing Dogs in the Kennel —");

        for (int i = 0; i < kennelDogs.length; i++) {

            kennelDogs[i].displayInfo();

        }

 

        // Make all dogs bark

        System.out.println("\n— Let the Dogs Bark! —");

        for (Dog dog : kennelDogs) {

            dog.bark();

        }

 

        // Rename a dog directly (if the field is public)

        System.out.println("\n— Renaming a Dog —");

        kennelDogs[0].name = "Buddy Jr.";

        kennelDogs[0].displayInfo();

    }

}

Explanation of the Example

  • Dog[] kennelDogs = new Dog[3]; creates an array with 3 references (all initially null).
  • Each element is then assigned a new Dog object using new Dog(…).
  • Two loops are used: a standard for-loop and an enhanced for-each loop.
  • We can modify properties of individual objects using their array index.

Example 2: Array of Student Objects

 // File: Student.java

public class Student {

    // Fields

    String name;

    int studentId;

 

    // Constructor

    public Student(String name, int studentId) {

        this.name = name;

        this.studentId = studentId;

    }

 

    // Method to display student information

    public void displayStudentInfo() {

        System.out.println("Student Name: " + name + ", ID: " + studentId);

    }

}

 

// File: Classroom.java

public class Classroom {

    public static void main(String[] args) {

        // 1. Declare an array to hold 4 Student objects

        Student[] classRoster = new Student[4];

 

        // 2. Instantiate and assign Student objects

        classRoster[0] = new Student("Alice", 1001);

        classRoster[1] = new Student("Bob", 1002);

        classRoster[2] = new Student("Charlie", 1003);

        classRoster[3] = new Student("Diana", 1004);

 

        // 3. Display all students in the classroom

        System.out.println("— Classroom Roster —");

        for (Student student : classRoster) {

            student.displayStudentInfo();

        }

 

        // 4. Find a student by ID

        int searchId = 1003;

        System.out.println("\n— Searching for Student with ID " + searchId + " —");

        boolean found = false;

        for (Student student : classRoster) {

            if (student.studentId == searchId) {

                System.out.print("Found: ");

                student.displayStudentInfo();

                found = true;

                break;

            }

        }

 

        // 5. If student not found

        if (!found) {

            System.out.println("Student with ID " + searchId + " not found.");

        }

    }

}

Explanation of the Example

  • The Student class includes fields, a constructor, and a method to display student info.
  • Student[] classRoster = new Student[4]; creates the array.
  • Each element is initialized with new Student(…).
  • We iterate through the array to display student details and search for a specific student.