Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
An abstract class is denoted in Visual Basic by the keyword MustInherit. In C#, the abstract modifier is used. Any methods that are meant to be invariant may be coded into the base class, but any methods that are to be implemented are marked in Visual Basic with the MustOverride modifier. In C#, the methods are marked abstract. The following example shows an abstract class:
// C#
abstract class WashingMachine
{
public WashingMachine()
{
// Code to initialize the class goes here.
}
abstract public void Wash();
abstract public void Rinse(int loadSize);
abstract public long Spin(int speed);
}
In the above example, an abstract class is declared with one implemented method and three unimplemented methods. A class inheriting from this class would have to implement the Wash, Rinse, and Spin methods. The following example shows what the implementation of this class might look like:
// C#
class MyWashingMachine : WashingMachine
{
public MyWashingMachine()
{
// Initialization code goes here.
}
override public void Wash()
{
// Wash code goes here.
}
override public void Rinse(int loadSize)
{
// Rinse code goes here.
}
override public long Spin(int speed)
{
// Spin code goes here.
}
}
When implementing an abstract class, you must implement each abstract (MustOverride) method in that class, and each implemented method must receive the same number and type of arguments, and have the same return value, as the method specified in the abstract class.