Wednesday, January 14, 2015

Interfaces Vs Abstract Classes


The abstract keyword enables you to create classes and class members that 
are incomplete and must be implemented in a derived class.


Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

Example:

class Program
{
    private interface IVehicle
    {
        void Move();
    }
    private abstract class Car : IVehicle
    {
        public abstract void Move();
        protected void Drive(string name)
        {
            Console.WriteLine("Drive " + name);
        }
    }
    private class Toyota : Car
    {
        public override void Move()
        {
            Drive("Toyota");
        }
    }
    private class Ford : Car
    {
        public override void Move()
        {
            Drive("Ford");
        }
    }
    private abstract class Bicycle : IVehicle
    {
        public abstract void Move();
        protected void Peddle(string name)
        {
            Console.WriteLine("Peddle " + name);
        }
    }
    private class Cannondale : Bicycle
    {
        public override void Move()
        {
            Peddle("Cannondale");
        }
    }
    private class Bianchi : Bicycle
    {
        public override void Move()
        {
            Peddle("Bianchi");
        }
    }
    private static void MoveDownStreet(List<IVehicle> vehicles)
    {
        Console.WriteLine(String.Empty);
        Console.WriteLine("Move IVehicles down the street");
        vehicles.ForEach(v => v.Move());
    }
    private static void MoveDownLeftLane(List<Car> cars)
    {
        Console.WriteLine(String.Empty);
        Console.WriteLine("Move Cars down left lane");
        cars.ForEach(c => c.Move());
    }
    private static void MoveDownBikeLane(List<Bicycle> bikes)
    {
        Console.WriteLine(String.Empty);
        Console.WriteLine("Move Bicycles down bike lane");
        bikes.ForEach(b => b.Move());
    }
    static void Main(string[] args)
    {
        var allvehicles = new List<IVehicle>();
        allvehicles.Add(new Toyota());
        allvehicles.Add(new Ford());
        allvehicles.Add(new Cannondale());
        allvehicles.Add(new Bianchi());
        MoveDownStreet(allvehicles);
        MoveDownLeftLane(allvehicles.Where(v => v.GetType().BaseType == typeof(Car)).Cast<Car>().ToList());
        MoveDownBikeLane(allvehicles.Where(v => v.GetType().BaseType == typeof(Bicycle)).Cast<Bicycle>().ToList());
    }
}


Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.

Abstract classes are faster than interfaces.

Another importance of interface is, in C#, interfaces will allow multiple inheritance which cannot be achieved using abstract classes.