CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces 157
As you can see, these are behaviors or characteristics that each new Galaxy object can do, or can
change, about its current existence (states or characteristics), including your Galaxy( ) constructor
method, which can actually create and initialize a new Galaxy object, which will represent and track
all the variables specified in Table 5-2.
Coding the Galaxy Class: Variable Declarations
Let’s add to our Hello Universe application example from the previous chapters, and create a new
Galaxy class that generates Galaxy objects for our existing Hello Universe application. To declare
this new class, which we will call Galaxy, we will utilize the following Java class creation syntax:
public class Galaxy { instance variables, constructor, and methods will go in here, between these
curly brackets }
Just as is the convention with any other modern programming language, the first items that we will
want to declare at the top of our Java Galaxy class are our instance variables, which we are going to
use to hold the attributes or states of our Galaxy objects. In Java, this is done by using the following
generalized format:
So, for our Galaxy object state instance variables that we described in the previous section, we
would write the variable description lines of code as follows, shown inside of the public Galaxy class
definition code structure:
public class Galaxy {
String galaxyName;
int galaxySolarSystems;
int galaxyPlanets;
long galaxyColonies;
double galaxyLifeforms;
int galaxyFleets;
int galaxyStarships;
}
Table 5-3. Galaxy Class Method (Behavior) Names, Along with Their Functionality Specifications
Name of Method: Functionality of Method:
Galaxy(constructor) Constructor method, which creates each Galaxy object instance
setGalaxyColonies Method allowing the number of Galaxy colonies to be set
getGalaxyColonies Method that returns the current number of Galaxy colonies
setGalaxyPopulation Method allowing the total population of the Galaxy to be set
getGalaxyPopulation Method that returns the current total population of the Galaxy
setGalaxyFleets Method allowing a total number of fleets in a Galaxy to be set
getGalaxyFleets Method that returns the current number of fleets in the Galaxy
setGalaxyStarships Method allowing the number of starships in the Galaxy to be set
getGalaxyStarships Method that returns the current number of starships in a Galaxy