Game Development Reference
In-Depth Information
make an actual instance of that class. You can only inherit from it. Abstract classes
can be useful when you want to design a class that serves as the basis of other
classes. You could also use an interface for that, but in an abstract class, you can
already define a few methods that can be useful to the classes that inherit from the
abstract class. For example, in the Stream class, the Read method is already defined
using the yet to be implemented ReadByte method.
You can even write your own abstract classes if you want to. An abstract class is
exactly the same as a regular class, instead that it has the keyword abstract in front
of the class. Furthermore, abstract classes can also have abstract methods. Abstract
classes are useful if you want to define what methods a subclass should implement
(similar to an interface), but, as opposed to an interface, abstract classes may already
define methods and properties. For example, the GameObject class could be a good
candidate for an abstract class, since we probably will not make an actual instance
of it, but we use it as a basic class to define the interface and behavior of subclasses.
Have a look at the following example:
abstract class GameObject
{
protected Vector2 position;
public GameObject()
{
this .position = Vector2.Zero;
}
public Vector2 Position
{
get { return position; }
set { position = value ;}
}
public abstract void Draw(GameTime gameTime, SpriteBatch spriteBatch);
}
The abstract GameObject class has a few methods and properties that are im-
plemented (the constructor method and the Position property). The Draw method
is abstract, meaning that it is not implemented, but it has to be implemented
by any subclass that inherits from the GameObject class. Since GameObject is
an abstract class and not an interface, we can define member variables such as
position , or properties/methods such as Position and the GameObject constructor
method.
The TextReader class is also a good example of an abstract class: we do not want
to make an instance of it, but we use it as a basic implementation structure for the
subclasses.
Search WWH ::




Custom Search