Game Development Reference
In-Depth Information
say you are creating an
InvinciBagel
object for your game, so you declare a
public In-
vinciBagel()
constructor method, using the following Java code structure:
public InvinciBagel() {
int lifeIndex = 1000; // Defines units of lifespan
int hitsIndex = 0;
// Defines units of damage
("hits" on the object)
String directionFacing = "E";
// Direction
that the object is facing
Boolean currentlyMoving = false; // Flag showing if
the object is in motion
}
This constructor method, when called using an
InvinciBagel mortimer =
new InvinciBagel();
Java method call, creates an
InvinciBagel
object named
mortimer
, with 1,000 units of life and no hits, that is facing e
ast
and that is not cur-
rently moving.
Next, let's explore the concept of
overloading
the constructor method, which you
learned about earlier (see the section “Java Methods: Java Core Function Code Con-
structs”), and create another constructor method that has parameters that allow you to
define the
lifeIndex and directionFacing variables of the InvinciBagel
object while
you are creating it. This constructor method looks like this:
public InvinciBagel(
int lifespan, String direction
) {
int lifeIndex;
int hitsIndex;
String directionFacing = null;
Boolean currentlyMoving = false;
lifeIndex = lifespan;
directionFacing = direction;
}
In this version the
lifeIndex
and
hitsIndex
variables at the top are initialized to
0,
the default value for an integer, so you do not have to use
lifeIndex = 0 or hitsIndex =
0 in
the code. The Java programming language accommodates method overloading, so
if you use an
InvinciBagel bert = new InvinciBagel(900, "W");
method call to instantiate
the InvinciBagel object, the correct constructor method
will be used to create the object. The InvinciBagel
object named
bert
would have a