158 CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces
We are not using any default values for these instance variables because that is something that we
are going to want to do in our constructor method parameter list and constructor Galaxy object
initialization code, which will create and initialize (set starting data values for) each Galaxy object
we create using a Java new keyword. Normally, you would declare only the data types and variable
names, and set the data values later, using your constructor method, which we will be looking at in
the next section. If you wanted to set the data values as part of the variable declaration, here is an
example of what that would look like with the galaxyName variable:
String galaxyName = "The Milky Way";
Coding Galaxy Objects: Constructor Method
Now let’s look at adding some functionality to the Galaxy class by adding in methods using Java
code that will start right after our variable definitions end. The first method we need to define is the
constructor method that has the same name as the class, so it will be called public Galaxy(parameter
list) and will create and initialize our Galaxy objects as we add them to our Universe.
The initialization code for the constructor method will live inside of the curly braces, which will
always define the beginning and end of each Java method that you create (code). This first Galaxy( )
method is the very special type of method called the constructor, and this constructor method’s Java
code would be written as follows:
public Galaxy (String name, int solarSys, int planets) {
galaxyName = name;
galaxySolarSystems = solarSys;
galaxyPlanets = planets;
galaxyColonies = 0;
galaxyLifeforms = 0;
galaxyFleets = 0;
galaxyStarships = 0;
}
Inside of this Galaxy( ) constructor, we take three important parameters for our new galaxy’s name,
number of solar systems, and number of planets, and we then set them using the = operator
inside of the constructor method, where we will also be initializing the other Galaxy object instance
variables to zero.
Creating Galaxy Functions: Coding Your Methods
Next, let’s code our other eight methods, which perform functions that check on (called “polling”
or “getting“) and modify (called “setting“) the state of our Galaxy’s component attributes or
characteristics. This will provide a number of useful “galaxy building” capabilities to the users of your
Hello Universe application. We are going to use the .set( ) and .get( ) method naming format, which is
commonly used throughout Android, so that you see the convention for how things are done in Java
(and Android) at its most fundamental level.