Game Development Reference
In-Depth Information
10.5.5 Sealed Methods
If you do not want a subclass of the class that you programmed to be able to override
a virtual function, you can define the method with the keyword
sealed
. Sealed meth-
ods cannot be changed anymore by a subclass. For example, suppose the header of
the
HandleInput
method of the
Ball
class would be given as follows:
public sealed override void
HandleInput(InputHelper inputHelper)
In this case, we can no longer override the method in a subclass of
Ball
.Soifwe
were to try this in the class
BouncingBall
(which inherits from
Ball
), we would get a
compiler error.
10.6 Hierarchies of Classes
10.6.1 A Subclass 'Is a Kind of' Base Class
We've seen several examples of classes inheriting from a base game object class in
this chapter. A class should only inherit from another class if the relationship be-
tween these two classes can be described as 'is a kind of'. For example: a
Ball
is
akindof
ThreeColorGameObject
, and a
Painter
is a kind of
Game
. In fact, the hierar-
chy does not end there. We could write another class that inherits from the
Ball
class,
such as
BouncingBall
, which could be a special version of a standard ball that bounces
off canisters instead of only colliding with them. And we could make another class
BouncingElasticBall
that inherits from
BouncingBall
, which is a ball that deforms ac-
cording to its elastic properties when it bounces against a canister. Every time we
inherit from a class, we get the data (encoded in member variables) and the behavior
(encoded in methods and properties) from the base class for free.
Commercial games will have a class hierarchy of different game objects with
many different levels. For example, you could imagine that for a game that takes
place in a city with a harbor, we would need many different classes for objects
commonly occurring in such an environment:
class
GameObject {a very generic class for describing game objects with a position and a
velocity.}
class
StationaryGameObject : GameObject {...}
class
Tree : StationaryGameObject {...}
class
House : StationaryGameObject {...}
class
MovingGameObject : GameObject {...}
class
Vehicle : MovingGameObject {...}
class
MotorizedVehicle : Vehicle {...}
class
Car : MotorizedVehicle {...}
class
Truck : MotorizedVehicle {...}