Game Development Reference
In-Depth Information
7.4.3 Accessing the Data in the
Cannon
Class
We have shown how to define a class that describes an object in the game. This
object groups together the data that belongs to the game object. These data can be
accessed by the methods that are part of the class. For example, the
Reset
method
assigns initial values to the member variables. However, sometimes we need to ac-
cess this data directly from other classes. For example, we may need to retrieve the
current position of the cannon, or we may need to know what the color of the cannon
is so that we can change the color of the ball that we are shooting. In the
Painter2
program, we could obtain this information easily because there was only one class
and all the member variables were in a single long list. Now, if we want for example
to access the
color
variable that belongs to the
cannon
object in the
Painter
class, we
could try something like this:
Color cannonColor = cannon.color;
Unfortunately, this is not allowed; the compiler will generate an error that the
color
variable is not accessible. This is because by default, member variables are only
accessible to methods that are inside the same class. So we can access the
color
variable in the
Reset
method because they are both in the
Cannon
class, but the same
variable is not accessible in the
HandleInput
method, because that method is in the
Painter
class.
This sounds like it is a bad thing. How are we going to change the color of the
cannon in the
HandleInput
method if this data is not accessible? We could add a
method called
SetColor
to the
Cannon
class that would get the color as a parameter
and that would change it:
public void
SetColor(Color col)
{
this
.color = col;
}
And we could add another method to the class called
GetColor
to retrieve the color
of the cannon:
public
Color GetColor()
{
return this
.color;
}
Sometimes, programmers call these kinds of methods
getters
and
setters
.Inmany
object-oriented programming languages, methods are the only way to access the
data inside an object, so for each member variable that needs to be accessible outside
of the class, programmers added a getter and a setter. As C# is a more modern
language, it provides a feature that is relatively new to object-oriented programming
languages, called
properties
. A property is a replacement for a getter and a setter. It