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
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;
private Address Address;
publicbool Equals(Person other)
{
return other.Equals(other.Name) &&
other.DateOfBirth == this.DateOfBirth &&
other.Address == this.Address;
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.
Thanks for the easiest explanation on this topic.
ReplyDeleteNice Article on Interface Vs. Abstract Class, Why and When .
ReplyDeleteThanks 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.
ReplyDeleteyaar kya likha hai.....maja aagaya......
ReplyDeleteReally helpful article. Helped clear my concepts :) Thanks for writing this... :)
ReplyDeleteThank you for clear explanation.
ReplyDeleteGreat explanation,Thanks for your post.
ReplyDeleteReally useful. Good work
ReplyDeleteGreat article .
ReplyDeletei came across a very good website which is useful for testing your capabilities csharp questions and answers
ReplyDeleteGood One
ReplyDeletecheck this one...Abstract Class and Interface
ReplyDeleteLing
I chanced upon to view your blog and found it very interesting. Great ... Keep it up!
ReplyDeleteAdvanced .Net training
I read your blog. It’s very useful for me. I have some new idea to share with you .
ReplyDeletephp training company in Ahmedabad
php live project training in ahmedabad
live project training in Ahmedabad
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
ReplyDeleteDigital Marketing Company in chennai
Digital Marketing Company in India
Flipkart deals & coupons
ReplyDeleteflipkart coupon code
flipkart coupons offer promo code
Amazon promo code
amazon offers
amazon offers and deals
amazon coupon code
amazon deal of the day
cleartrip promo codes
cleartrip coupon code
cleartrip offers and deals
cleartrip deals
MMT promo Codes
MMT coupon codes
Makemytrip promo codes
makemytrip offers
makemytrip deals & offers
healthkart coupon code
healthkart promo codes
healthkart deals and offers
healthkart discount offers
Nice blog..it was so informative..keep update selenium training in chennai
ReplyDeleteselenium training in velachery
ReplyDeleteYour blog on RPA is so attractive that i am not able to stop myself to read this blog of yours on RPA.This blog contains all the important topics and points of RPA. Requesting you keep updating this post on RPAand help them who is eager to gain knowledge on RPA.
Thanks and Regards,
Uipath training in chennai
blue prism training institute in chennai
blue prism training with certification in chennai
Its really nice and informative.. Thanks for sharing
ReplyDeletePhp Training Institute in noida sector 16,
PlSql Training Institute in Noida sector 16,
Python Training Institute in Noida sector 16,
RPA Training Institute in Noida sector 16,
Salesforce Training Institute in Noida sector 16,
Sap fico Training Institute in Noida sector 16,
ERP Sap mm Training Institute in Noida Sector 16,
Sap Training Institute in Noida Sector 16,
SAS Training Institute in Noida Sector 16,
Blue Prism Training Institute in Noida,
thanks a lot for sharing this content.
ReplyDeletehome tutor
home tutor
home tutor
home tutor
home tutor
I took the overview of your content and found it informative. I think it will be helpful in my future work. Thanks you for such a wonderful post.
ReplyDeleteVideo Games Guide
Video Games Guide
Video Games Guide
Video Games Guide
Video Games Guide