Click here to Skip to main content
15,920,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Since we have to redefine all the methods predeclared in the interface then why we need to create interface and implement then in other classes?
Posted

Before constructing classes we can choose those features we plan to implement inside them. Next we can act in two ways which are to use abstract class or to create interface.

In my last application that was quite simple first i created 3 interfaces (IReader, IWriter, IAuthenticate) and then created classes to have access to data.
 
Share this answer
 
Lets say I develop a control that among other things supports sorting of class instances. You want to use my control. How am I supposed to know how to sort your particular class when I don't know it even exists?

I could make you inherit from an abstract class of my own - but that makes no sense as it would imply that I am providing a base implementation that you can override if desired. As I have no knowledge of your class there is no real way to provide a base implementation that would be of any use. Also, you would not be able to derive from any other classes (no multiple inheritance in C#).

Alternatively I can provide you with an interface and leave all the implementation up to you. Because I know you will have a Sort method, I can call it from my code without even knowing about your class! All my control needs to do is have a method that takes a parameter of that interface and we all have the result you desire.
 
Share this answer
 
An interface is a contract. It tells others that your class supports certain methods - it doesn't say how they are implemented, only that those methods are present. What this means, in practice, is that you can accomplish the same thing in many different ways; absolutely invaluable if you want to use something like Inversion of Control (IoC).

As an example, if you want to use the using pattern in C# then your class must implement IDisposable. Behind the scenes, the compiler translates the using block into the following:
SomeClass someClass = null;
try
{
  someClass = new SomeClass();
}
finally
{
  ((IDisposable)someClass).Dispose();
}
There you see someClass being cast to IDisposable which allows the application to call Dispose.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900