Sometimes you might want a class to inherits from more than one parent class. For example, you might define a Vehicle class that has vehicle properties such as MaxSpeed, and a Domicile class with house-like properties such as SquareFeet. You might then like to make a HouseBoat or MotorHome class that inherits from both Vehicle and Domicile.
Unfortunately C# does not allow multiple inheritance. A class can inherit from at most one parent class. However, a class can implement any number of interfaces so, instead of true multiple inheritance, you can use interface inheritance. In this example, you can make HouseBoat inherit from Domicile and implement the IVehicle interface.
Even if you make HouseBoat implement IVehicle, there are a couple of odd issues.
First, if IVehicle defines a MaxSpeed property, you still can't access it directly from HouseBoat the way you could if it truly inherited from a Vehicle class.
Second, if you have some code that you would like to put in a Vehicle class, the HouseBoat class cannot inherit it because it only implements IVehicle--it doesn't really inherit from it.
To solve the second problem, this example uses the following Vehicle class. This class implements IVehicle and provides code that other classes can "inherit."
|