[OOP] – Differences between Abstract and Interface?

A very common interview question: The differences between abstract and interface?

Interface

Think of interface as the USB port on your flashdrive. When buying a new laptop, you don’t think “does it compatible with my flahsdrive”, but you think “does it have a USB port?”. And you know that every single computer on this planet will compatible with your flashdrive, as long as they have a USB port.

usb ports

Now look at this example

public interface IVehicle
{
    // make the vehicle run
    void Run();

    // get the percent of fuel left in tank
    double GetFuelLeft();
}

And this implementation

public class Motorbike : IVehicle
{
    public void Run()
    {
        // code to make the motobike run
    }

    public double GetFuelLeft()
    {
        // code to get the percent number of fuel left in tank
    }
}

public class Car : IVehicle
{
    public void Run()
    {
        // code to make the car run
    }

    public double GetFuelLeft()
    {
        // code to get the percent number of fuel left in tank
    }
}

So every class that inherit from IVehicle will be able to Run, and GetFuelLeft, no matter what kind of vehicle it is.

Note that each type of vehicle will have a different way to make it run, have different fuel tank, so to get the percentage of fuel in the tank, we need different method.

Abstract

So, what if all vehicle have the same fuel tank (unlikely, but just assume it’s true)? A same method to get the fuel in the tank for every vehicle. In this case, we can use abstract class

public interface IVehicle
{
    // make the vehicle run
    void Run();
}

public abstract class SameFuelTankVehicle
{
    public double GetFuelLeft()
    {
        // code to get the percentage of fuel left
    }
}

and now the implementation

public class Motorbike : SameFuelTankVehicle, IVehicle
{
    public void Run()
    {
        // code to make it run
    }
}

now Motorbike use the same method to get percentage of fuel just like any class that inherit SameFuelTankVehicle, but it have a different method to make it run

Conclusion

Interface is functionalities oriented. It declares which functionalities a class must have.

Abstract is object oriented. It offers the basic data an object will have and/or functions it should be able to do.

from this SO answer

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.