Java: An array of objects

Sometimes, we might want to create an array of objects.  This is done by creating an array of instance.

Here we create an array class Rock and using an instance called r, we initialize the object using the constructor.

package javaapplication42;

public class Music {

    static public class Rock {

        int TopTen = 0;

        public Rock(int t) {
            this.TopTen = t;
        }

        public void count() {
            System.out.println(TopTen);
        }
    }
    
    public static void main(String[] args) {

        Rock[] r = new Rock[3];
       r[0] = new Rock(10); 
       r[0].count();
       
       r[1] = new Rock(2); 
       r[1].count();

       r[2] = new Rock(5); 
       r[2].count();

    }
}

arrayobject

Series Navigation<< Java: Abstract class
Java: A simpler abstract class example >>