Inheritance
[Agent practical 4 of 9]
Next, we'll look at our class that is going to do most of the work: Nibbler.
Here it is:
Download it to your practical directory and open it in Notepad++.
So, this class extends Animal
. This means that it doesn't need its own x
, getX()
,
y
, getY()
, or world
variable. All these things are inherited from
Animal, and because they're protected
in the superclass they can be used as if they were in
Nibbler and yet be private to all the other classes.
Note the use of the constructor here carefully. Nibbler's constructor calls super
(the superclass Animal's constructor)
and passes in the Environment object. In the Animal constructor, the Environment object is captured in the world
instance variable, and x
and y
are set to default values. Once the Animal constructor has run, control is
passed back to the subclass Nibbler's constructor. Here we still have two lines to run:
x = (int)(Math.random() * world.getWidth());
y = (int)(Math.random() * world.getHeight());
These lines immediately set x
and y
to new values -- a random location within the world -- obliterating the work done to these
variables in the Animal constructor. To generate this random location the Nibbler constructor
uses the world
variable just set up and inherited from Animal. Neat hu? Neat, if a little crazy to get your head round. It it
helps, imagine the two classes, Animal and Nibbler, as one -- with all their code merged.
Lastly, note that Nibbler finally has a fully coded run()
. This run() overrides the superclass run()
-- not because the latter is
empty, but because if a subclass and superclass contain the same method declaration, the subclass always wins. In such circumstances, the only simple way
to get the superclass method to run is to call super.run()
.
Note that for clarity, we've taken the opportunity to split run()
into its constituent parts, each with its own method. This makes the
sequence of what goes on in run() much more explicit. We can easily see that it involves moving the agent and then interacting with the Environment.
Once you're ok with the above, compile the new copies of your files, and convince yourself they work. We'll then look at adding a stopping criteria to our model.