15 June 2012

Interface Vs. Abstract Class, Why and When

Recently many people asked me this question - what is the difference between an abstract class and an interface? - This is a typical interview question and you can easily find answers like below in any .NET book.
  • abstract classes can contain pure abstract methods as well as concrete methods. But all methods in an interface are implicitly abstract
  • Methods in an abstract class can be protected, private, static etc. But, all items in an interface are implicitly public
  • A class can inherit multiple interfaces, but it can inherit only one abstract class.
  • etc. :)
But, in my view, one shouldn't compare interfaces and abstract classes because each of them have their own strength and weaknesses. I have also seen many people who go dumbfounded if someone asks them - Why do you use an interface? Or Why do you use an abstract class? I suggest you to go through this MSDN  page which gives you an idea of when to use what. In this blog, I will try to explore my knowledge on these two concepts.

Abstract Class
 
An abstract class is just another class with abstract keyword. But, the keyword 'abstract' adds some additional features to the class like - the class can contain just method declarations, an instance of the class cannot be created. So, below one is an abstract class.
 
public abstract class Animal
{
   public void Walk()
   {
      Console.WriteLine("Walking");
   }
   public void Sleep()
   {
      Console.WriteLine("Sleeping");
   }
   public abstract void Eat();
}
 
This class defines the basic characteristics of an animal like every animal sleeps, Moves, eats etc. But look at the Eat function. I have made it abstract in the sense - every animal can eat but what it eats depends upon the kind of animal.
 
class Cow : Animal
{
   public override void Eat()
   {
      Console.WriteLine("Eating grass");
   }
}
class Tiger : Animal
{
   public override void Eat()
   {
      Console.WriteLine("Eating meat");
   }
}
 
I hope above example doesn't need any explanation. You can see that abstract class defines an IS-A relationship. Which means Cow is an Animal, so Cow has all the basic characters of an Animal. e.g. Move and Sleep functions need not be re-defined in Cow class.

Also note that, If I add any new behaviour to base class, child classes need not be changed at all and they simply inherit the new behaviour. For example, if I define a new behaviour 'Drink' in animal class, both the child classes simply adapt the new behaviour immediately.

public abstract class Animal
{
   ...
   public void  Drink()
   {
       Console.WriteLine("Drinking water");
   }
   public abstract void Eat();
}
 
So, visioning is not a problem when you use abstract class. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface. Hence, If you want to create multiple versions of your component, create an abstract class.

One more thing to be noted that all these 2 classes Tiger, Cow are closely related i.e. both are Animals and share common behaviour of an animal. So, when the classes are closely related and share common functionality - Use Abstract classes. 

Interfaces 

In contrast to abstract class, an Interface defines a CAN-DO relationship rather than IS-A relationship. For example, the definition of String class looks like below,
 
class String : IComparable, ICloneable, IConvertible
..
 
This definition tells you that - you can compare string objects, you can clone string objects, you can convert string objects into other type.

Next thing is, when the classes are not closes related and you still want to have a common functionality among them - Use Interfaces. Let's consider an example,

 
public interface IEquatable<T>
{
   bool Equals(T other);
}
public class Person: IEquatable<Person>
{
   private string Name;
   private DateTime DateOfBirth;
   public bool Equals(Person other)
     {
      return other.Equals(other.Name) && other.DateOfBirth == this.DateOfBirth;
   }
}
public class Home : IEquatable<Home>
{
   private int HouseNumber;
   private int AreaCode;
   public bool Equals(Home other)
   {
       return other.AreaCode == this.AreaCode && other.HouseNumber == this.HouseNumber;
   }
}

 
Here 2 non-related classes Home and Person want to have Equality function. See that functionality 'Equals' is common between the 2 classes but the implementation is completely different. Hence, both Home & Person implement IEquatable interface but implement Equals method independently.

Now you can ask, if the implementations are different, what is the need of using interface? Of course, just remove the IEquatable interface and the program still works. So, why interface? Let me try to make it clear step by step.

Firstly, An interface acts as a CONTRACT. This means, any class that implements an interface agrees to implement all the methods in that interface. Also note that, (ideally) once implemented, interface (contract) definition cannot change i.e. you cannot add new methods and modify existing ones in an interface. This is very important aspect of interfaces. This assures the consumer of your class that, the class will implement all the methods defined in the interface contract though the implementation can change. For example, I know that Person class implements IEquatable interface. Hence I am guaranteed that Person class always contains Equals method. Hence, I am ensured that my below code always works.

IEquatable<Person> person1 = new Person();
IEquatable<Person> person2 = new Person();
bool areTheyEqual = person1.Equals(person2);

Having this, a new version of Person class is released and Equals method now includes a check for address of person also.
public class Person: IEquatable<Person>
{
   privatestring Name;
   private DateTime DateOfBirth;
   private Address Address;
   publicbool Equals(Person other)
     {
      return other.Equals(other.Name) &&
             other.DateOfBirth == this.DateOfBirth &&
             other.Address == this.Address;
   }
}

See that, though the implementation has changed, my consumer code  still works. So, having an interface implemented makes your class Backward compatible.

Secondly, interfaces are quite useful when you want call a method on dynamic object. For example, below helper function prints all the items in a collection - A List, Array, String etc.

public void DisplayAllItems<T>(IEnumerable<T> collection)
{
   foreach (var item in collection)
   {
       Console.WriteLine(item);
   }
}

In the above function, you can pass a List, array or any object that implements IEnumerable interface. Otherwise, we would need to implement the display logic for each collection type separately.

These are 2 examples of why to use interfaces. There are other lot of reasons for using interfaces like laying out complex architectures, implementing design patterns etc. But, I hope this blog gives you an idea of why to use interfaces.

That concludes the discussion of differentiating between interface & abstract class, which one to prefer & when. I hope you enjoyed reading my blog. Please put your feedback which help me in improving myself and also to help others.

27 comments:

  1. Thanks for the easiest explanation on this topic.

    ReplyDelete
  2. Nice Article on Interface Vs. Abstract Class, Why and When .

    ReplyDelete
  3. Thanks for giving such a nice blog for this topic.. really Awesome.but i need some easy example of interface like abstract class example without using generic. so please can u provide simple example so i can understand easily.

    ReplyDelete
  4. yaar kya likha hai.....maja aagaya......

    ReplyDelete
  5. Really helpful article. Helped clear my concepts :) Thanks for writing this... :)

    ReplyDelete
  6. Great explanation,Thanks for your post.

    ReplyDelete
  7. i came across a very good website which is useful for testing your capabilities csharp questions and answers

    ReplyDelete
  8. I chanced upon to view your blog and found it very interesting. Great ... Keep it up!

    Advanced .Net training

    ReplyDelete
  9. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in dot net programming your post help me a lot.Thanks for your informative article.Dot Net training in chennai | dot net training and placement | Dot Net training in velachery

    ReplyDelete
  10. Thanks for appreciating. Really means and inspires a lot to hear from you guys.I have bookmarked it and I am looking forward to reading new articles. Keep up the good work..Believe me, This is very helpful for me
    Digital Marketing Company in chennai
    Digital Marketing Company in India

    ReplyDelete
  11. Cloud Computing Training In Noida
    Webtrackker is IT based company in many countries. Webtrackker will provide you a real time projects based training on Cloud Computing. If you are looking for the Cloud computing training in Noida then you can join the webtrackker technology.
    Cloud Computing Training In Noida , Cloud Computing Training center In Noida , Cloud Computing Training institute In Noida ,

    Company Address:
    Webtrackker Technology
    C- 67, Sector- 63, Noida
    Email: info@webtrackker.com
    Website: www.webtrackker.com
    http://webtrackker.com/Cloud-Computing-Training-Institutes-In-Noida.php

    ReplyDelete
  12. Video editing course in Noida
    Video editing training institute in Noida- Webtrackker Technology is and IT Training institute providing the Video editing course in Noida, FCP, Final Cut Pro Training in Noida. For more call us- 8802820025.
    Video editing course in Noida
    best video editig course in noida
    best video edtitng institute in noida
    Company Address:
    Webtrackker Technology
    C- 67, Sector- 63, Noida
    Phone: 01204330760, 8802820025
    Email: info@webtrackker.com
    Website: http://webtrackker.com/Best-training-institute-Video-editing-FCP-course-in-Noida.php

    ReplyDelete