Abstraction and Interface


#1

Hi, i here to know about difference between Abstraction and Interface with example code that help me in my learning. Hoping for valuable suggestions.


#2

How about that?
http://www.codeproject.com/Articles/814367/Interfaces-and-Abstract-Classes


#3

To make it short and to the point, the only difference between these two is the fact that you can have implementation in an abstract class.

Now, it’s really a matter of choice but you will most likely want to use an abstract class to encapsulate common, related functionality whereas you will want to use an interface to provide a unified protocol to unrelated objects but still have the same API.

Here is a simplistic example for an abstract class but you should get the point:

abstract class Dog
{
    public void Bark()
    {
        BarkingVoice();
        
        Console.WriteLine("Barking");
    }

    protected virtual void BarkingVoice()
    {
    }
}

class Labrador : Dog
{
    protected override void BarkingVoice()
    {
    }
}

Here is an example for an interface:

interface ICanGetHaircut
{
    void GetHaircut();    
}

abstract class Dog : ICanGetHaircut
{
    public void Bark()
    {
        BarkingVoice();
        
        Console.WriteLine("Barking");
    }

    protected virtual void BarkingVoice()
    {
    }

    public void GetHaircut()
    {
        Console.WriteLine("Getting an haircut.");
    }
}

class Human : ICanGetHaircut
{
    public void GetHaircut()
    {
        Console.WriteLine("Getting an haircut.");
    }
}

Hopefully this gives you a brief overview of what it is and where you should use it.


.NET Foundation Website | Blog | Projects | Code of Conduct