Why do both the abstract class and interface exist in C#?

前端 未结 11 1970
渐次进展
渐次进展 2020-12-03 00:00

Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract.

Is it because:

11条回答
  •  心在旅途
    2020-12-03 00:31

    The idea is simple - if your class(YourClass) is already deriving from a parent class(SomeParentClass) and at the same time you want your class(YourClass) to have a new behavior that is defined in some abstract class(SomeAbstractClass), you can't do that by simply deriving from that abstract class(SomeAbstractClass), C# doesn't allow multiple inheritance. However if your new behavior was instead defined in an interface (IYourInterface), you could easily derive from the interface(IYourInterface) along with parent class(SomeParentClass).

    Consider having a class Fruit that is derived by two children(Apple & Banana) as shown below:

    class Fruit
    {
        public virtual string GetColor()
        {
            return string.Empty;
        }
    }
    
    class Apple : Fruit
    {
        public override string GetColor()
        {
            return "Red";
        }
    }
    
    class Banana : Fruit
    {
        public override string GetColor()
        {
            return "Yellow";
        }
    }
    

    We have an existing interface ICloneable in C#. This interface has a single method as shown below, a class that implements this interface guarantees that it can be cloned:

    public interface ICloneable
    {
        object Clone();
    }
    

    Now if I want to make my Apple class(not Banana class) clonable, I can simpley implement ICloneable like this:

     class Apple : Fruit , ICloneable
    {
        public object Clone()
        {
            // add your code here
        }
    
        public override string GetColor()
        {
            return "Red";
        }
    }
    

    Now considering your argument of pure abstract class, if C# had a pure abstract class say Clonable instead of interface IClonable like this:

    abstract class Clonable
    {
        public abstract object Clone();
    }
    

    Could you now make your Apple class clonable by inheriting the abstract Clonable instead of IClonable? like this:

    // Error: Class 'Apple' cannot have multiple base classes: 'Fruit' & 'Clonable'
    class Apple : Fruit, Clonable
    {
        public object Clone()
        {
            // add your code here
        }
    
        public override string GetColor()
        {
            return "Red";
        }
    }
    

    No, you can't, because a class cannot derive from multiple classes.

提交回复
热议问题