In the previous lesson you saw how to use the Java APIs.
Using classes and methods
Methods provide the means of telling an object what it can do.
In this series of lessons you will learn:
- Methods which change an object's state
- Overloading and inheritance
- Abstract classes and methods
Methods that modify an object's state
The Animal class allows its instance variables to be set from the constructor, but only currently provides methods which return those values to client objects[1]. Although it is unlikely that an animal's name or gender could change it is still a possibility (if, for example, the entries were wrongly entered to begin with) and the age value will naturally change on an annual basis.
To this end, you will now define three additional methods within Animal that enables these values to be changed, starting with a method to change the animal's name:
Note the following about the new method:
- The method is
publicso objects from any package can invoke it. - The
voidkeyword means that a value is not returned from this method. There is no need to return anything since its purpose is merely to modify an internal instance variable. - The method is called
setName()where the prefix "set" is a commonly adopted convention for naming methods that modify an object's state.
The methods to change the gender and age follow a similar pattern (from now on, surrounding code won't always be shown to save space):
The new methods can be invoked (for example from the VirtualZoo class) as follows:
In the next lesson you will learn how to overload methods: