This is one of the topics in programming languages that we (programmers) get to "fairly" understand after a good experience. I remember my initial months in programming when I knew what is an interface, how it is different from an abstract class, etc. etc. But it always left me wondering, why "really" do we need interfaces? I could not give myself a good justification of the need for interfaces. I just knew the "what" part of it. But "why" part was absolutely missing.
I hope this blog will help few of our friends who are still trying to understand this concept. Let's understand this topic in a question-answer format.
A. What is an interface?
Now, what is a contract?
Contract is a set of properties, methods, events or indexers defined in an interface. If a class implements an interface, the contract is to implement the members defined in the interface. Its a must to implement all of them. If not, c# would give a compile time error.
Compile time errors are actually good. Obviously it's better to get issues at compile time than run time.
* All interface members have to be public.
B. Why use interfaces?
Let's understand this with following scenario.An application is being designed. The basic requirement is, that the application should be able to connect to any Database in the market.In order to understand why use interface, let's see what problems we face if we do not use interfaces. For simplicity and to concentrate on the real problem the example has no way to get a connectionstring.
Solution-1 : Using Concrete class
The above solution, just leads to a run-time exception! That's the disadvantage of using concrete class in this scenario. There is no contract and so no compile time exception even if a basic implementation is missed out.
Solution-2 : Using Abstract class
Abstract class has members that are declared but not implemented. Those are implemented by the child classes that inherit from the abstract class.
In the above example, we get a compile time exception. The compiler is forcing us to implement to OpenConnection method. This is definately better than a run time exception!
Solution-3 : Using Interface
Interfaces are constructs that only have method declaration and no implementation of any method at all. They are similar to a pure abstract classes that too have no implementation.
Output
Similar to abstract classes, interfaces too if not implemented give a compile time exception. The compiler is forcing us to implement all the methods declared in an interface. As mentioned before, interface is a contract to implement all the members.
Conclusion
Its better to have compile time exception by using Abstract class or interfaces. That leaves us with a question...What to choose abstract class or an interface? To help make that decision, one has to know the restrictions and advantages of each of them. The next blog on differences between abstract classes and interfaces will help one choose based on needs!