Java Reference
In-Depth Information
circleArray
circleArray[0]
Circle
object 0
reference
circleArray[1]
Circle
object 1
…
circleArray[9]
Circle
object 9
F
IGURE
9.19
In an array of objects, an element of the array contains a reference to an
object.
Listing 9.11 gives an example that demonstrates how to use an array of objects. The pro-
gram summarizes the areas of an array of circles. The program creates
circleArray
, an
array composed of five
Circle
objects; it then initializes circle radii with random values and
displays the total area of the circles in the array.
L
ISTING
9.11
TotalArea.java
1
public class
TotalArea {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Declare circleArray
5 CircleWithPrivateDataFields[] circleArray;
6
7
// Create circleArray
8 circleArray = createCircleArray();
9
10
array of objects
// Print circleArray and total areas of the circles
11
printCircleArray(circleArray);
12 }
13
14
/** Create an array of Circle objects */
15
public static
CircleWithPrivateDataFields[] createCircleArray() {
16 CircleWithPrivateDataFields[] circleArray =
17
new
CircleWithPrivateDataFields[
5
];
18
19
for
(
int
i =
0
; i < circleArray.length; i++) {
20 circleArray[i] =
21
new
CircleWithPrivateDataFields(Math.random() *
100
);
22 }
23
24
// Return Circle array
25
return
circleArray;
return array of objects
26 }
27
28
/** Print an array of circles and their total area */
29
public static void
printCircleArray(
30 CircleWithPrivateDataFields[] circleArray) {
31 System.out.printf(
"%-30s%-15s\n"
,
"Radius"
,
"Area"
);
32
for
(
int
i =
0
; i < circleArray.length; i++) {
33 System.out.printf(
"%-30f%-15f\n"
, circleArray[i].getRadius(),
34 circleArray[i].getArea());
35 }
36
37 System.out.println(
"—————————————————————————————————————————-"
);
38
39
// Compute and display the result
40 System.out.printf(
"%-30s%-15f\n"
,
"The total area of circles is"
,
41
pass array of objects
sum(circleArray) );
42 }
Search WWH ::
Custom Search