

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Elements of an array can be of any type, and when applied to objects, this can prove very practical and useful. For example, consider collecting data on a group of children. We might have multiple arrays to store their names, ages, heights, and genders. String[] name = new String[MAX_CHILDREN]; int[] age = new int[MAX_CHILDREN]; double[] height = new double[MAX_CHILDREN]; char[] gender = new char[MAX_CHILDREN]; Arrays of the same length, carrying data on different aspects of a problem, are sometimes called parallel arrays. Rather than four parallel arrays for our study, we could use a single array of objects. class Child { private String name; // family, given private int age; // in years private double height; // in metres private char sex; // M or F } Child[] patient = new Child[MAX_CHILDREN]; So far, this has created an array where each element can refer to a Child object. We have not yet, however, created any actual Child objects. To accomplish this, we could traverse the array, and create an object for each element. for (int i = 0; i < patient.length; i++) { patient[i] = new Child(); } It is only with this second fragment of code that we actually invoke the constructor for the Child class, which will create the necessary Child objects in memory. In this case, all of the information about the first child can be referenced through patient[0], such as patient[0].age or patient[0].sex. There are a number of advantages to using an array of objects rather than multiple arrays of data.
parameters.
fields in the object class. The parameter lists of any methods remain unchanged.
through the use of accessor and mutator methods.
Exercises
height, and gender) for a child on two lines with the name on the first line and the other data on the second line. Print the height in centimetres, rounded to the nearest centimetre.
chosen to use parallel arrays rather than an array of objects to represent our data.
class Fraction { private int num; private int den; public Fraction (int n, int d) { num = n; den = d; } }