By Tony Bevis on Sunday, 08 October 2023
Category: Java

Java programming course: 3.1 Using classes and methods

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 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:

[1] A "client object" is any other object that invokes a method of the current object.

 Note the following about the new method:


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:

Lesson 3.2 Method overloading

Related Posts

Leave Comments