Java Reference
In-Depth Information
the
Person
class constructor: a name and a string indicating what the person says when he sees a change
in Dr. Jekyll. You add each of the observers for the
man
object in the
for
loop.
Calling the
drinkPotion()
method for
man
causes the internal name to be changed, the
setChanged()
method to be called for the
man
object, and the
notifyObservers()
method that is inherited from the
Observable
class to be called. This results in the
update()
method for each of the registered observers
being called, which generates the output. If you comment out the
setChanged()
call in the
drinkPo-
tion()
method, and compile and run the program again, you get no output. Unless
setChanged()
is
called, the observers aren't notified.
Now let's move on to look at the
java.util.Random
class.
GENERATING RANDOM NUMBERS
You have already used the
Random
class a little, but let's investigate this in more detail. The
Random
class
enables you to create multiple random number generators that are independent of one another. Each object
of the class is a separate random number generator. Any
Random
object can generate pseudo-random num-
bers of types
int
,
long
,
float
, or
double
. These numbers are created using an algorithm that takes a
seed
and
grows
a sequence of numbers from it. Initializing the algorithm twice with the same seed produces the
same sequence because the algorithm is deterministic.
The integer values that are generated are uniformly distributed over the complete range for the type, and
the floating-point values are uniformly distributed over the range 0.0 to 1.0 for both types. You can also
generate numbers of type
double
with a
Gaussian
(or normal) distribution that has a mean of 0.0 and a
standard deviation of 1.0. This is the typical bell-shaped curve that represents the probability distribution for
many random events.
Figure 15-3
illustrates the principle flavors of random number generators that you can
define.