Learn to Create an Array of Objects in Java
Introduction
Object-oriented programming is a fundamental feature of Java, which is why so much of the work gets done with objects. As we know, arrays can contain elements of primitive types and dynamically create objects of the same type. An array is a container for objects in Java. A class in Java is also a user-defined data type. The term array of objects refers to an array of class-type elements. These elements are the reference of the object.
Creating an Array of Objects
The first step in creating an array of objects is to create an instance of the class using the new keyword. The following statements can help create an array of objects.
Syntax
ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects |
Or
ClassName[] objArray; |
Or
ClassName objeArray[]; |
An Array Of Objects Declaration In Java
To declare an array of objects, we use the class name Object, followed by square brackets.
Object[] JavaObjectArray; |
An alternative way to declare an array of objects can be:
Object JavaObjectArray[]; |
Here are some other things we can do with an array of objects.
An array of Objects Declared With Initial Values.
Adding initial values to an array of objects is an easy way to declare the array.
Using the below code, we create an array that contains a string named Board Infinity and an integer named 5.
public class Main { |
Array Of Objects: Initialization
The array of objects must get initialized with values after being instantiated. As an array of objects differs from an array of primitive types, it cannot get initialized like a primitive type array. An array of objects requires initialization for each element, i.e., each object. The objects in an array are references to the actual class.
Therefore, after declaring and instantiating an array of objects, it is recommended to create actual objects of the class. The constructors can initialize the array. By passing values to the constructor, the program can assign initial values to actual objects. An object can also be assigned data via a separate member method in a class.
Example
class Employee { |
Code Sample
The following code will demonstrate how to use an Array of Objects in Java.
public class ArrayExample { |