1

I'm studying C# with videos, and I got a question.

When achieving Polymorphism, what's the difference between achieving it via Interface and via Overriding?

I think they're both good in extensibility, cause they can both simply create a new class to extend.

Are there better points if we use Interface to achieve Polymorphism? Or it just depends on the circumstances?

Any abstract or theoretical answer is fine. Thank you.

jaemin kim
  • 11
  • 1
  • 1
    Possible duplicate of [Interface vs Abstract Class (general OO)](https://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo) – Tebogo Khanye Nov 12 '17 at 09:06
  • 1
    Useful links: [OOP Concepts](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/object-oriented-programming), [Abstract Classes](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract), [Interfaces](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface) – Tebogo Khanye Nov 12 '17 at 09:16
  • 1
    You get polymorphism through interfaces. You get inheritance through overriding. They are two separate concepts. And "both simply create a new class to extend" - no, they do not - neither of them do that. – Enigmativity Nov 12 '17 at 10:59

2 Answers2

1

If you need shared methods or properties for implementation classes, you can use abstract class instead of interface. So, i provided an example below.

As you see, for interface example MessageText methods are shared for two implementations.

public interface IMessageSender
{
    void SendMessage();
}
public class EmailSender : IMessageSender
{
    public void SendMessage()
    {
        Console.WriteLine(MessageText());
    }
    private string MessageText()
    {
        return "Message to send !";
    }

}
public class SmsSender : IMessageSender
{
    public void SendMessage()
    {
        Console.WriteLine(MessageText());
    }

    private string MessageText()
    {
        return "Message to send !";
    }
}

You can use abstract class for shared methods or properties like this;

public abstract class MessageSender
{
    public abstract void SendMessage();

    protected string MessageText()
    {
        return "Message to send !";
    }
}
public class EmailSender : MessageSender
{
    public override void SendMessage()
    {
        Console.WriteLine(MessageText());
    }

}
public class SmsSender : MessageSender
{
    public override void SendMessage()
    {
        Console.WriteLine(MessageText());
    }
}
lucky
  • 12,734
  • 4
  • 24
  • 46
0

With the help of interface you can achieve multiple inheritance also while if you use abstract class and method overriding, this is not possible to achieve multiple inheritance C#. More over the use of interface will help you to achieve dependency injection (you may learn about it later) and reduce dependency of your code.