Java Reference
In-Depth Information
The class Hunter inherits the methods of all interfaces ( act and draw , in this case) as abstract
methods. It must, then, provide method definitions for both of them by overriding the methods,
or the class itself must be declared abstract.
The Animal class shows an example where a class does not implement an inherited interface
method. Animal , in our new structure in Figure 10.4, inherits the abstract method act from
Actor . It does not provide a method body for this method, which makes Animal itself abstract
(it must include the abstract keyword in the class header).
The Animal subclasses then implement the act method and become concrete classes.
Exercise 10.56 Challenge exercise Add a non-animal actor to the simulation. For instance,
you could introduce a Hunter class with the following properties. Hunters have no maximum
age and neither feed nor breed. At each step of the simulation, a hunter moves to a random
location anywhere in the field and fires a fixed number of shots into random target locations
around the field. Any animal in one of the target locations is killed.
Place just a small number of hunters in the field at the start of the simulation. Do the hunters re-
main in the simulation throughout, or do they ever disappear? If they do disappear, why might
that be, and does that represent realistic behavior?
What other classes required changing as a result of introducing hunters? Is there a need to
introduce further decoupling to the classes?
Interfaces as types
When a class implements an interface, it does not inherit any implementation from it, because
interfaces cannot contain method bodies. The question, then, is: What do we actually gain by
implementing interfaces?
When we introduced inheritance in Chapter 8, we emphasized two great benefits of inheritance:
The subclass inherits the code (method implementations and fields) from the superclass. This
allows reuse of existing code and avoids code duplication.
The subclass becomes a subtype of the superclass. This allows polymorphic variables and
method calls. In other words, it allows different special cases of objects (instances of sub-
classes) to be treated uniformly (as instances of the supertype).
Interfaces do not provide the first benefit (because they do not contain implementations), but
they do provide the second. An interface defines a type just as a class does. This means that
variables can be declared to be of interface types even though no objects of that type can exist
(only subtypes).
In our example, even though Actor is now an interface, we can still declare an Actor variable
in the Simulator class. The simulation loop still works unchanged.
Interfaces can have no direct instances, but they serve as supertypes for instances of other
Search WWH ::

Custom Search