Game Development Reference
In-Depth Information
In this example, we have a Base class that has three member variables, each with
different access modifiers. Inside the someMethod method (point A), we can execute
the following instructions without any problem:
publicVar = 10;
protectedVar = 5;
privateVar = 1;
This is because within the class where a member variable is declared, we can always
access this member variable. Now suppose that we are inside the someOtherMethod
(point B), which is defined in the Derived class. Since Derived inherits from Base ,it
contains a Base instance. This means that Derived also has three member variables
which it has inherited from Base . However, we can only execute the following two
instructions inside the someOtherMethod method:
publicVar = 10;
protectedVar = 5;
If we try to access the privateVar variable here, it will result in a compiler error,
because this variable was declared private , meaning that only the class in which it
was declared can access it directly. However, we do have access to both the publicVar
and protectedVar variables, because public variables can be accessed by anyone, and
protected variables can be accessed within the base class, or within any method of a
derived class. Finally, we can only access the publicVar variable in the Update method
(point C):
d.publicVar = 10;
Trying to access either protectedVar or privateVar in the d object would result in a
compiler error, because the SomeGame class is unrelated to the Base and Derived
classes, it only uses them.
In the ThreeColorGameObject class, we did not yet provide any access modifiers
for the member variables. If there is no access modifier before a member variable
declaration, the C# compiler assumes that the member variable is private. So,
Texture2D currentColor;
is equivalent to
private Texture2D currentColor;
In our case, we would like that classes that inherit from ThreeColorGameObject
can access the member variables. Therefore, we declare the member variables in
ThreeColorGameObject as follows:
Search WWH ::




Custom Search