/** * FractionArrayTest class * * @author Erica Eddy * @version December 2010 * * This class demonstrates how allocating and using * an array of objects differs from that of allocating * and using an array of primitives. */ public class FractionArrayTest { // instance variables private int [] num; // an array of integers (primitives) private Fraction [] frac; // an array of objects (Fractions) private int numberOfFracs; // keeps track of number of positions filled // Constructor // declares both arrays // needs to initialize the number of elements in the object array public FractionArrayTest() { num = new int[5]; frac = new Fraction[5]; numberOfFracs = 0; } // fill array // Each object must be instantiated in order to fill the object array public void fillArray() { num[0] = 5; num[1] = 2; num[2] = 4; num[3] = 6; num[4] = 1; Fraction temp = new Fraction(5,75); frac[0] = temp; frac[1] = new Fraction(1,1); numberOfFracs = 2; } // print array contents // the loop to print the object array must depend on the number of // array slots filled, not the object array length public void printArray() { for (int i = 0; i < num.length; i++) System.out.println("num[" + i + "] = " + num[i]); for (int k = 0; k < numberOfFracs; k++) System.out.println("frac[" + k + "] = " + frac[k].toString()); } }