Array of Objects –
Module 3
An array of objects is used to store multiple
instances of a class within a single array.
This allows us to easily manage a collection of
objects when working with large datasets or
collections.
An array that contains class type elements is known
as an array of objects. It stores the reference variable
of the object.
Array of
Object
By using the class name and ‘new’ keyword
If I have a class named Employee, then can create an array of
object as
How to
create an ClassName obj[]=new ClassName[array_length]; //
array of declare and instantiate an array of objects
object
Employee obj[] = new Employee[5];
Employee is the name of class, obj[] is the array and 5 is the
size of array. That measns you can store 5 objects in this array.
EXAMPLE 1
• Defining the Product
class
• This class holds two attributes: an integer pro_Id (product ID)
and a string pro_name (product name).
• These attributes represent the properties of a “product.”
• Constructor for the
Product class
• This constructor is called whenever we create a new Product
object.
• It takes two parameters (pid and n) and assigns them to the
class attributes pro_Id and pro_name.
• It allows us to create Product objects with a specific ID and name.
• The display() method in
Product
• When called, this method prints out the product’s
details (its ID and name).
• System.out.print is used to print on the same line,
followed by System.out.println() to move the cursor to
the next line afterward.
• Creating an array of Product
objects • obj is an array that can hold references to Product objects.
• Initially, this line creates space for 5 Product references but
does not create the Product objects themselves yet.
• Instantiating actual Product
objects
• Here, each element of the array obj is assigned a
new Product object using the constructor.
• We pass a productId and a productName to each
new Product.
• For each element in the array, we:
• Print a header like "Product Object 1:".
• Call display() on the corresponding Product object
(e.g., obj[0].display()), which prints the product’s ID
and name.
• Example 2 : Demonstrate how to create an array of Student objects and initialize them with different
values. Then, we will display the details of each student object stored in the array.
• The for loop
iterates over each
Student object in
the “s" array. Inside
the loop,
s1.display() is
called to print the
details of each
Student object.