CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces 159
You might be wondering: “Why not code an .addGalaxyColonies( ) method?” The answer is that
then you would also have to code a .subtractGalaxyColonies( ) method call, for when any colonies
were destroyed by starship fleets! By having a .setGalaxyColonies( ) method, we can add and
subtract colonies in our gameplay code logic, and simply call a .setGalaxyColonies( ) method when
we are done to update the Galaxy object galaxyColonies data value in either direction, up or down.
The first .setGalaxyColonies( ) method is much simpler than our Galaxy( ) constructor method, and
it will allow us to set the number of colonies in our Galaxy object. The Java code for this method
would be written as follows:
void setGalaxyColonies (long numberColonies) {
galaxyColonies = numberColonies;
}
The void return data type that is declared before our .setGalaxyColonies( ) method name declares
what type of data value will be returned by this method. In this case, the method does not return any
data value at all, thus we’ll declare it as being of the void return data type (that is, devoid of any data
return type or return data value).
Also note that our method name begins with a lowercase letter, and uses uppercase letters for
words that are internal to the method name. Inside the .setGalaxyColonies( ) method body, we’ll
utilize an assignment operator that sets the galaxyColonies instance variable to the value in the
numberColonies long parameter.
In Java programming, assignment operators are how we set the values of instance variables, which
we declare at the head, or top, of our Java class.
We will do something very similar with the .setGalaxyPopulation( ) method, which will look like this,
once we code it in Eclipse ADT, which we will be doing a little bit later on in this chapter:
void setGalaxyPopulation (double numberLifeforms) {
galaxyLifeforms = numberLifeforms;
}
Next, let’s code our .setGalaxyFleets( ) method, which lets us set the number of starship fleets
in our Galaxy objects. This method will set the galaxyFleets count instance variable, using the
assignment operator, as shown in the following Java method construct:
void setGalaxyFleets (int numberFleets) {
galaxyFleets = numberFleets;
}
Finally, let’s code our .setGalaxyStarships( ) method, which lets us set the number of starships in
our galaxy. This method will set the galaxyStarships count variable, using the assignment operator,
as is shown in the following Java method construct:
void setGalaxyStarships (int numberStarships) {
galaxyStarships = numberStarships;
}