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:
public class Animal {
// Declare instance variables to hold an animal's attributes
private String name; // the animal's name
private String gender; // the animal's gender ("m" or "f")
private int age; // the animal's age in years
// Define constructor
public Animal(String myName, String myGender, int myAge) {
name = myName;
gender = myGender;
age = myAge;
}
// Define instance methods
// Return the animal's name
public String getName() {
return name;
}
// Change the animal's name
public void setName(String newName) {
name = newName;
}
// Return the animal's gender
public String getGender() {
return gender;
}
// Return the animal's age
public int getAge() {
return age;
}
// Rest of class will go here...
}
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):
// Change the animal's gender
public void setGender(String newGender) {
gender = newGender;
}
// Change the animal's age
public void setAge(int newAge) {
age = newAge;
}
The new methods can be invoked (for example from the VirtualZoo class) as follows:
Animal bruno = new Animal("Bruno", "m", 4);
// Change bruno's details
bruno.setName("Bruuuuno");
bruno.setGender("f"); // She was a girl all along!
bruno.setAge(5); // and now a year older
// Output bruno's details
System.out.println("Name: " + bruno.getName());
System.out.println("Gender: " + bruno.getGender());
System.out.println("Age: " + bruno.getAge());
In the next lesson you will learn how to overload methods:
Comments