Game Development Reference
In-Depth Information
public void
HandleInput(InputHelper inputHelper)
{
if
(inputHelper.KeyPressed(Keys.R))
Color = Color.Red;
else if
(inputHelper.KeyPressed(Keys.G))
Color = Color.Green;
else if
(inputHelper.KeyPressed(Keys.B))
Color = Color.Blue;
−
position.Y;
double
opposite = inputHelper.MousePosition.Y
−
position.X;
double
adjacent = inputHelper.MousePosition.X
angle = (
float
)Math.Atan2(opposite, adjacent);
}
This method has the exact same header as the one in the
ThreeColorGameObject
class, except that the body is different. However, the C# compiler does not auto-
matically assume that we want to replace the original
HandleInput
method. This is
not because the compiler is stupid, but it is because overriding a method has quite
a big impact on the behavior of a class, so it is better to be very explicit about
it. This is why we have to use the
override
keyword to indicate that we are over-
riding a method. The header of the
HandleInput
method in the
Cannon
class then
becomes:
public override void
HandleInput(InputHelper inputHelper)
But does this mean that any class that inherits from the
GameObject
class can override
all its methods without any problem? No, in fact we can indicate in the
GameObject
class which methods we are allowed to override. Only the methods that carry the
keyword
virtual
can be overridden. This means that if we want subclasses to over-
ride the
HandleInput
method from
GameObject
, we need to change the header in the
ThreeColorGameObject
class to
public virtual void
HandleInput(InputHelper inputHelper)
As you can see in the
ThreeColorGameObject
class definition provided in the example,
all of its methods are virtual. This means that any of its methods can be overridden.
This mechanism is very important to govern what a class can do when it inherits
from another class, because in some cases it is not desirable that a subclass can
override any method it likes. For example, the
Game
class allows you to override
its
Update
and
Draw
methods, but not the
Run
method. The reason is that the
Run
method does all kinds of low-level things that we do not want any subclasses to
mess around with. By making this distinction between methods that are virtual and
methods that are not, we can shield parts of the base class from the subclasses so
that the programmer of the subclass cannot do any serious harm when overriding
methods and extending the base class.