Game Development Reference
In-Depth Information
5.3.3 A Constructor Describes How an Object Is Created
When a
SpriteBatch
object is created using the
new
keyword, we need to provide
some information so that this object can be created, namely the graphics device.
This information is passed as a parameter to a special method called the
construc-
tor
method. Inside this method, we put all the instructions needed to initialize our
object. A constructor method has a special header: it carries the same name as the
class. The
Balloon
class contains a constructor method, which looks as follows:
public
Balloon()
{
Content.RootDirectory = "Content";
graphics =
new
GraphicsDeviceManager(
this
);
}
Just like a normal method, the constructor method has parentheses which may con-
tain parameters (in this case there are no parameters). And just like a normal method,
a constructor method has a header and a body.
5.3.4
this
: The Object We Are Currently Manipulating
When we create the instance of our
Balloon
class in the
Main
method, the
Balloon
constructor method will be called. Inside the constructor method, we set the root
directory where all assets are placed, and we initialize the graphics device. The first
line looks like we are accessing a property
RootDirectory
from the class
Content
.How-
ever, this is not what happens. In fact,
Content
is a
property
of the
Game
class, and
because
Balloon
is a special version of that class, it also has the
Content
property.
But if properties need an object, which object is this property manipulating? It ma-
nipulates the object that is currently created. So, in the
Main
method, we create an
instance of the
Balloon
class and store it in the variable
game
. The instructions in the
constructor method then manipulate this object.
This object has a variable
graphics
. We assign the graphics device to that variable,
which we create by constructing an instance of the
GraphicsDeviceManager
class. The
constructor method of this class needs a variable of type
Game
, which we need to
pass as a parameter. Of course, we want to pass our variable
game
to this constructor.
However, if we would write the following line in the constructor, we would get a
compiler error:
graphics =
new
GraphicsDeviceManager(game);
The reason for this is that the variable
game
is declared in the
Main
method, and
because of the variable scope rule discussed in the previous chapter, we can
only
access this variable in the method is was declared in
. What we in fact want to do is to