Game Development Reference
In-Depth Information
10.4.3 Accessing Member Variables from the Base Class
So how about accessing member variables that are declared in the base class? As
you can see in the overridden
HandleInput
method, we access the
position
member
variable which is declared in the
ThreeColorGameObject
class. So does that mean that
a subclass can access any member variable it likes? No. Also in this case, the base
class decides who can access its member variables. For this, there are three different
keywords that are used:
public
,
private
and
protected
. These keywords are also called
access modifiers
since they change how members of a class can be accessed. If we
use the
private
access modifier, only the class itself can access the member variable.
This member variable is then called a
private member variable
. A class can never
access private member variables of another class.
A protected member variable can be accessed from within the class in which
it is declared, or from within any class that inherits from that class, but not from
any other (unrelated) classes. Finally, a public member variable can be accessed
by anyone (including unrelated classes). Let us look at an example to see how this
works. Consider the following classes:
class
Base
{
public int
publicVar;
protected int
protectedVar;
private int
privateVar;
void
someMethod()
{
A
}
}
class
Derived : Base
{
void
someOtherMethod()
{
B
}
}
class
SomeGame : Game
{
Othermembervariablesandmethods
protected override void
Update(GameTime gameTime)
{
Derived d =
new
Derived();
C
}
}