Page 437 - Introduction to Programming with Java: A Problem Solving Approach
P. 437

                Apago PDF Enhancer
SalesClerk[] clerks = new SalesClerk[4];
clerks[0] = new SalesClerk("Daniel", 6.25);
clerks[1] = new SalesClerk("Josh", 58.12);
clerks[2] = new SalesClerk("Amanda", 77.46);
Can’t Access Array Data Directly
With an array of primitives, you can access the array’s data, the primitives, directly. For example, the fol- lowing code fragment shows how you can assign and print the first rainfall value in a rainfall array. Note how the value is directly accessed with rainfall[0].
double[] rainfall = new double[365];
rainfall[0] = .8;
System.out.println(rainfall[0]);
On the contrary, with an array of objects, you normally cannot access the array’s data, the variables inside the objects, directly. Since the variables inside the objects are normally private, you normally have to call a constructor or method to access them. For example, the following code fragment shows how you can use a constructor to assign Daniel and 6.25 to the first object in the clerks array. It also shows how you can use accessor methods to print the first object’s name and sales data.
SalesClerk[] clerks = new SalesClerk[4];
clerks[0] = new SalesClerk("Daniel", 6.25);
System.out.println(
clerks[0].getName() + ", " + clerks[0].getSales());
10.10 Arrays of Objects 403
 clerks
    clerks[0] clerks[1] clerks[2] clerks[3]
null
Daniel, 6.25 Josh, 58.12 Amanda, 77.46
     Figure 10.20 An array of objects that stores sales-clerk sales data
Need to Instantiate Array of Objects and the Objects in That Array
With an array of primitives, you perform one instantiation—you instantiate the array object and that’s it. But with an array of objects, you have to instantiate the array object, and you must also instantiate each element object that’s stored in the array. It’s easy to forget the second step, the instantiation of individual element objects. If you do forget, then the elements contain default values of null, as illustrated by clerks[3] in Figure 10.20. For the empty part of a partially filled array, null is fine, but for the part of an array that’s supposed to be filled, you need to overlay null with a reference to an object. The following is an example of how to create an array of objects—more specifically, how to create the clerks array of objects shown in Figure 10.20. Note the separate instantiations, with the new operator, for the clerks array and for each SalesClerk object.












































































   435   436   437   438   439