Java Reference
In-Depth Information
new Person("Officer","What's all this then?"),
new Person("Eileen Backwards", "Oh, no, it's horrible - those teeth!"),
new Person("Phil McCavity", "I'm your local dentist - here's my card."),
new Person("Slim Sagebrush", "What in tarnation's goin' on here?"),
new Person("Freaky Weirdo", "Real cool, man. Where can I get that stuff?")
};
// Add the observers
for(int i = 0; i < crowd.length; i++)
man.addObserver(crowd[i]);
man.drinkPotion(); // Dr. Jekyll drinks up
}
}
If you compile and run this, you should get the output:
It's Mr.Hyde
Freaky Weirdo: Real cool, man. Where can I get that stuff?
It's Mr.Hyde
Slim Sagebrush: What in tarnation's goin' on here?
It's Mr.Hyde
Phil McCavity: I'm your local dentist - here's my card.
It's Mr.Hyde
Eileen Backwards: Oh, no, it's horrible - those teeth!
It's Mr.Hyde
Officer: What's all this then?
How It Works
JekyllAndHyde
is a very simple class with just two methods. The
drinkPotion()
method encourages
Dr. Jekyll to do his stuff, and the
getName()
method enables anyone who is interested to find out who he is.
The class extends the
Observable
class so we can add observers for an object of this class.
The revamped
Person
class implements the
Observer
interface, so an object of this class can observe
an
Observable
object. When notified of a change in the object being observed, the
update()
method will be called. Here, it just outputs who the person is, and what they say.
In the
Horrific
class, after defining Dr. Jekyll in the variable
man
, we create an array,
crowd
, of type
Observer
to hold the observers - which are of type
Person
, of course. We can use an array of type
Observer
because the class
Person
implements the
Observer
interface. We pass two arguments to
the
Person
class constructor: a name, and a string that is what the person will say when they see a
change in Dr. Jekyll. We add each of the observers for the object
man
in the
for
loop.
Calling the
drinkPotion()
method for the object
man
results in the internal name being changed, the
setChanged()
method being called for the
man
object, and the
notifyObservers()
method that is
inherited from the
Observable
class being called. This causes the
update()
method for each of the
registered observers to be called, which generates the output. If you comment out the
setChanged()
call in the
drinkPotion()
method, and compile and run the program again, you'll 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.