Java Reference
In-Depth Information
43
44
/** Add circle areas */
45
public static double
sum(CircleWithPrivateDataFields[] circleArray) {
pass array of objects
46
// Initialize sum
47
double
sum =
0
;
48
49
// Add areas to sum
50
for
(
int
i =
0
; i < circleArray.length; i++)
51 sum += circleArray[i].getArea();
52
53
return
sum;
54 }
55 }
Radius Area
70.577708 15649.941866
44.152266 6124.291736
24.867853 1942.792644
5.680718 101.380949
36.734246 4239.280350
—————————————————————————————————————————————-
The total area of circles is 28056.687544
The program invokes
createCircleArray()
(line 8) to create an array of five circle
objects. Several circle classes were introduced in this chapter. This example uses the
Cir-
cleWithPrivateDataFields
class introduced in Section 9.9, Data Field Encapsulation.
The circle radii are randomly generated using the
Math.random()
method (line 21).
The
createCircleArray
method returns an array of
CircleWithPrivateDataFields
objects (line 25). The array is passed to the
printCircleArray
method, which displays the
radius and area of each circle and the total area of the circles.
The sum of the circle areas is computed by invoking the
sum
method (line 41), which takes
the array of
CircleWithPrivateDataFields
objects as the argument and returns a
dou-
ble
value for the total area.
9.27
✓
✓
What is wrong in the following code?
Check
Point
1
public class
Test {
2
public static void
main(String[] args) {
3 java.util.Date[] dates =
new
java.util.Date[
10
];
4 System.out.println(dates[
0
]);
5 System.out.println(dates[
0
].toString());
6 }
7 }
You can define immutable classes to create immutable objects. The contents of
immutable objects cannot be changed.
Key
Point
Normally, you create an object and allow its contents to be changed later. However, occa-
sionally it is desirable to create an object whose contents cannot be changed once the object
has been created. We call such an object as
immutable object
and its class as
immutable
class
. The
String
class, for example, is immutable. If you deleted the setter method in the
CircleWithPrivateDataFields
class in Listing 9.9, the class would be immutable,
because radius is private and cannot be changed without a setter method.
immutable object
immutable class
Search WWH ::
Custom Search