Java Tutorial: Array of Objects

, , …,

You can make a array of Objects in Java. Here is a example.

class H {
    int x;
    H (int n) {x=n;}

public class Ar4 {
    public static void main(String[] args) {
        H[] myA;
        myA = new H[4];

        for (int i = 0; i < myA.length; i++) {
            myA[i] = new H(i);
            System.out.print(new Integer(myA[i].x) +" ");

Note the line H[] myA;. It declares that the variable myA is a datatype of array of H. The line myA = new H[4]; assigns this variable myA a thing, and that thing is a array of 4 elements, and each element is of type H.

The line myA[i] = new H(i); sets the value for each slot of myA. And, that value being the instantiation of H with i as the init parameter to the constructor of H.