Hello fellow programmers,
I am reading a book on C# and the author is comparing Abstract classes and Interfaces. He claims that if you have the following "abstract class:"
abstract class CloneableType
{
public abstract object Clone();
}
Then you cannot do this:
public class MiniVan : Car, CloneableType
{}
This, I understand. However he claims that because of this inability to do multiple inheritance that you should use an interface for CloneableType, like so:
public interface ICloneable
{
object Clone();
}
My question is, isn't this somewhat misleading, because you can create an abstract class which is "above" class Car with the method Clone, then have Car inherit that class and then Minivan will inherit Car with all these methods, CloneAble class -> Car class -> Minivan Class.
What do you think? Thanks.
ICloneable
like this is usually not a good idea. You would end up casting the result anyways, so there is no reason to use an interface (or abstract class) here.MiniVan
than inherits fromCar
; instead, you want a classVehicle
, with properties of typesChassis
,Wheel
,Engine
, etc., and make those polymorphic. This is known as Composition, and you should favor code reuse through composition over code reuse through inheritance whenever possible.IEnumerable
interface type for a parameter and not have to care about the particular implementation. You cannot achieve the same with a class hierarchy - you will end up dragging a much bigger view into an object (if you will) than you actually need.