Java Reference
In-Depth Information
simulation by providing further implementations of the
SimulatorView
interface. The new
class
GraphView
, which produces the line graph, is an example of this.
Once we have more than one view implementation, we can easily replace the current view
with another or, as we have in our example, even display two views at the same time. In the
Simulator
class, the concrete subclasses
GridView
and
GraphView
are only mentioned once
when each view was constructed. Thereafter, they are stored in a collection holding elements of
the
SimulatorView
supertype, and only the interface type is used to communicate with them.
The implementations of the
GridView
and
GraphView
classes are fairly complex, and we do not
expect you to fully understand them at this stage. The pattern of providing two implementations for a
single interface, however, is important here, and you should make sure that you understand this aspect.
Exercise 10.61
Review the source code of the
Simulator
class. Find all occurrences
of the view classes and interfaces, and trace all variables declared using any of these types.
Explain exactly how the views are used in the
Simulator
class.
Exercise 10.62
Implement a new class
TextView
that implements
SimulatorView
.
TextView
provides a textual view of the simulation. After every simulation step, it prints out
one line in the form
Foxes: 121 Rabbits: 266
Use
TextView
instead of
GridView
for some tests. (Do not delete the
GridView
classes.
We want to have the ability to change between different views!)
Exercise 10.63
Can you manage to have all three views active at the same time?
10.8
The
Class
class
In Chapter 8, we described the paradoxically named
Object
class. It shouldn't surprise you,
therefore, that there is also a
Class
class! This is where talking about classes and objects can
become very confusing.
We used the
Class
type in defining the
SimulatorView
interface in the previous section. The
Class
class has nothing specifically to do with interfaces; it is a general feature of Java, but we
just happen to be meeting it for the first time here. The idea is that each type has a
Class
object
associated with it.
The
Object
class defines the method
getClass
to return the
Class
associated with an object.
Another way to get the
Class
object for a type is to write “
.class
” after the type name: for
instance,
Fox.class
or
int.class
—notice that even the primitive types have
Class
objects
associated with them.
Class
objects are particularly useful if we want to know whether the type of two objects is the
same. We use this feature in the original
SimulatorView
class to associate each animal type
with a color in the field.
SimulatorView
has the following field to map one to the other:
private Map<Class, Color> colors;
Search WWH ::
Custom Search