locked
Why do we need Interfaces? RRS feed

  • Question

  • Hi,

    I am not able to understand the significance of the interfaces.

    Interfaces exposes some behavior through methods, but classes can also expose its behavior through public methods directly, then why do we want to use the interfaces?

    is it just for an assurence that all the methods in the interfaces are inplemented in the class? Is there any other reason like performance?

    I guess interface object will/can not be created at runtime, is it correct? if so then how does the communication happen at runtime?

    any thoughts/links to understand "what an interface is?".

    Thanks and Regards,

    Benin.

    Monday, January 8, 2007 12:53 PM

Answers

  • Hi,

    Suppose you have an application that has two types of people: Customer and Employee. Both Customer and Employee can subscribe to an event. The procedure of subscribing is different. Customers need to pay and subscbribe where as Employees only need to subscribe.

    When you have a list of objects (both Customers and Employees) that want to subscribe, you need to check for each object what type of person it is before knowing how it needs to subscribe to the event. If at a certain point you add a different person type, you need to add additional code in the calling class.

    With interfaces this can be a lot easier. First we create an interface named IPerson. This interface has a method named Subscribe. Than we make sure that all the person types implement this interface. The method Subscribe is implemented in the classes (Customer, Employee).

    If we need to have a list of persons we create the list as follow:
    List<IPerson> myList = new List<IPerson>();

    IPerson person1 = new Customer();
    myList.Add(person1);

    IPerson person2 = new Employee();
    myList.Add(person2);

    Now when we loop through the list, we can use IPerson.Subscribe() to subscribe a person. This will cause the .NET framework to call the Subscribe method from the objects class.

    Interfaces make it easier to extend this type of code. When a different person type is needed, you only need to add a class that implements the IPerson interface.

    Let me know if the above is not clear.

    Greetz,

    Geert

     

    Geert Verhoeven
    Consultant @ Ausy Belgium

    My Personal Blog

    Monday, January 8, 2007 1:12 PM
  • http://www.codersource.net/csharp_tutorial_interface.html
    http://www.codeguru.com/csharp/csharp/cs_syntax/interfaces/article.php/c7563/
    http://msdn2.microsoft.com/en-us/library/ms173156.aspx

    I'm not saying that I truely understand the meaning of interfaces but I wanted to provide you some links.

    Hope this helps!

     

    Timo

    Monday, January 8, 2007 1:00 PM
  • Hi

    this is a question i've heard before...

    one of the principles of object oriented programming is the abstraction or separation if you wish, of the interface and the implementation of classes.

    consider, for example the IDbCommand interface in the system.data namespace.
    Regardless if the object's instance is a SqlCommand or a OledbCommand
    you can use the IDbCommand interface to "command" the object.

    so there you have the reusability of the code...

    However, an interface is more..
    an interface is the public face of a class, even if you don't explicitly declare it.
    consider the following:

    public class Test{
    public void DoSomething()
    public void DoSomethingElse()
    private void DoSomethingPrivate()
    }

    the two public methods, and any public properties can be considered as the interface of the class,
    so, i guess you could say that anything that is accessible for outside the class is it's interface...

    now, declaring an interface explicitly, is adding a layer of abstraction,
    which can come in handy later, if you want to add a second class that needs to implement it (reuse of code)
    but generally it's saying, or rather commiting to a number of behaviours by your class (separation of code and interface)

    Hope this sheds some light ;)

     

    Monday, January 8, 2007 9:17 PM
  • Hi,

    Its difficult to explain the real-time benefits of interfaces, abstract cls etc in such a short span/space. So let me conclude few of the things..

    Interfaces
    - Allows multiple inheritance, extensibility, runtime polymorphism, abstraction/data hiding, easy maintainance/management etc ... long list of benefits but finally all depends on your application requirements....
    e.g if you wish that a Human will have some specific characteristics, some of then can be found in other species and some of them are specific to the human then you can have IHuman (for human specific), ISpecies (common to all species) etc and you can impl these in Human

    So Human implements IHuman, ISpecies

    Now ISpecies can be implemented in Animal class to so this class can be implemented from IAnimal, ISpecies

    In concrete class or abstract class this is not possible. you can inherit from only ONE class while multi interface can be allowed.

    So if you have such requirement then you must use interfaces to reduce repeating code, good maintainability.

    Also lets say if you have created ISpecies and you have derived Human class then its possible that ISpecies can be used in future for Animal class or something like that etc then fur extensibility point of view its good to have it.

    Its basically OOP design concepts why you need to use interfaces.

    If yo have a very small application which has not future extension requirement and straight forward impl then you dont worry about interfaces but in else can you should...

    Also there is another benefit which is already explained in some post for your reply... that if you have two diff objects consiting same method then you can use interface to call that method without worring that which actual object it is.
    e.g. Lets say,
    public void AssignColor (IShape objShape) {
    objShape.Color = "Blue";
    }
    here, lets say IShape has a property named Color and you have a common method to assign color then you dont need to worry that which object is being passed wheter its Square, Triangle or something else.[which impl IShape]
    so AssignColor(objSqare) and AssignColor(objTriangle) both can work without changing your code. Even in future if you add some more shapes using IShape then also this method will work for them also.

    This way LOTS of real-time uses are there but all depends on your application need.

    But this is what i have faced so far that if your project is even a small project, then also its always good to follow OOPs concepts which will give you lots of future benefits.

    May be if you are not much aware/experienced using OOPs designs then it will be difficult to visualize the benefits but the fact is, I always used to use OOPs even in a smallest application. It can give you benefits but if not then also it will never harm you...

    Please find on google about differences between "Interfaces vs. classes" and "Interfaces vs. Abstract classes" etc, and read just top 5-10 links, you will get enough information.

    HTH,

    Tuesday, January 9, 2007 10:42 AM
  • Well if you know that you are dealing with only one type, and will never have a second type then no you don't need to use interfaces, but interfaces are useful when you want extensible code, you don't have to use them but if you do they make your life a lot easier.

    Say for example you want to create a sorting algorithm, and you want it to work with any type of object, an easy way to do this is to write you're sorting class to operate on objects that implement a certain interface, say sortable. Without interfaces you would have to write a new class or method for any new classes you wish to sort, but if you use interfaces you just have to write one class that has one method that takes in a sortable object as it's parameter, and it will just work.

    Like anything in programming they aren't something that you absolutly have to use but they are a tool that can be used to create elegant and powerful code.

    Monday, January 8, 2007 2:17 PM
  • Hi

    an abstract base class differs have some similarities

    they both provide a number of methods, properties and so on that are common to it's children and implementors

    but... a base class can define a code body (which can or can not be overriden),

    while an Interface only defines method signatures

    also, for inheritance i try and look at the "is a" rule

    so base class company
    child class client is a company
    child class supplier is a company

    all these can implement the

    public  interface IIdentifiable{
    int id {get set};
    DateTime LastSave{get;set;}
    }

    which is not to say that interfaces can only be used for "util" purposes...

    Hope this helps you out!

    Tuesday, January 9, 2007 8:57 AM

All replies

  • http://www.codersource.net/csharp_tutorial_interface.html
    http://www.codeguru.com/csharp/csharp/cs_syntax/interfaces/article.php/c7563/
    http://msdn2.microsoft.com/en-us/library/ms173156.aspx

    I'm not saying that I truely understand the meaning of interfaces but I wanted to provide you some links.

    Hope this helps!

     

    Timo

    Monday, January 8, 2007 1:00 PM
  • Hi,

    Suppose you have an application that has two types of people: Customer and Employee. Both Customer and Employee can subscribe to an event. The procedure of subscribing is different. Customers need to pay and subscbribe where as Employees only need to subscribe.

    When you have a list of objects (both Customers and Employees) that want to subscribe, you need to check for each object what type of person it is before knowing how it needs to subscribe to the event. If at a certain point you add a different person type, you need to add additional code in the calling class.

    With interfaces this can be a lot easier. First we create an interface named IPerson. This interface has a method named Subscribe. Than we make sure that all the person types implement this interface. The method Subscribe is implemented in the classes (Customer, Employee).

    If we need to have a list of persons we create the list as follow:
    List<IPerson> myList = new List<IPerson>();

    IPerson person1 = new Customer();
    myList.Add(person1);

    IPerson person2 = new Employee();
    myList.Add(person2);

    Now when we loop through the list, we can use IPerson.Subscribe() to subscribe a person. This will cause the .NET framework to call the Subscribe method from the objects class.

    Interfaces make it easier to extend this type of code. When a different person type is needed, you only need to add a class that implements the IPerson interface.

    Let me know if the above is not clear.

    Greetz,

    Geert

     

    Geert Verhoeven
    Consultant @ Ausy Belgium

    My Personal Blog

    Monday, January 8, 2007 1:12 PM
  • If I understood correctly,

    Irrespective of the object's type we can assign it to the Interface type and call the implemented funtion (without knowing the type of object).

    But what is the significance of Interface while I am dealing with only one Type (either a Customer or an Emploee)? Does Interface matters there?

    Still I couldn't understand the real Need for the interface :(.

    What are difficulties do we have to face if there are no Interfaces? (Is that 'we have to find the type of object and call the appropriate funtion' the (only) problem? But even this can be achived without interface)

    Is there any situation which can only be achived through Interfaces? (please bear with me:-) )

     

    Thanks and Regards,

    Benin.

    Monday, January 8, 2007 2:01 PM
  • Well if you know that you are dealing with only one type, and will never have a second type then no you don't need to use interfaces, but interfaces are useful when you want extensible code, you don't have to use them but if you do they make your life a lot easier.

    Say for example you want to create a sorting algorithm, and you want it to work with any type of object, an easy way to do this is to write you're sorting class to operate on objects that implement a certain interface, say sortable. Without interfaces you would have to write a new class or method for any new classes you wish to sort, but if you use interfaces you just have to write one class that has one method that takes in a sortable object as it's parameter, and it will just work.

    Like anything in programming they aren't something that you absolutly have to use but they are a tool that can be used to create elegant and powerful code.

    Monday, January 8, 2007 2:17 PM
  • Hi

    this is a question i've heard before...

    one of the principles of object oriented programming is the abstraction or separation if you wish, of the interface and the implementation of classes.

    consider, for example the IDbCommand interface in the system.data namespace.
    Regardless if the object's instance is a SqlCommand or a OledbCommand
    you can use the IDbCommand interface to "command" the object.

    so there you have the reusability of the code...

    However, an interface is more..
    an interface is the public face of a class, even if you don't explicitly declare it.
    consider the following:

    public class Test{
    public void DoSomething()
    public void DoSomethingElse()
    private void DoSomethingPrivate()
    }

    the two public methods, and any public properties can be considered as the interface of the class,
    so, i guess you could say that anything that is accessible for outside the class is it's interface...

    now, declaring an interface explicitly, is adding a layer of abstraction,
    which can come in handy later, if you want to add a second class that needs to implement it (reuse of code)
    but generally it's saying, or rather commiting to a number of behaviours by your class (separation of code and interface)

    Hope this sheds some light ;)

     

    Monday, January 8, 2007 9:17 PM
  • Thank you. Now I could think of the uses of Interface somewhat.

    I got one more doubt, How does it differ from an Abstract/Base class?

    Is there any specific reason/requirement to use Abstract class/Interface?

    When sohuld we go for an abstract class and for Interface?

    Thanks and Regards,

    Benin.

    Tuesday, January 9, 2007 6:39 AM
  • Hi

    an abstract base class differs have some similarities

    they both provide a number of methods, properties and so on that are common to it's children and implementors

    but... a base class can define a code body (which can or can not be overriden),

    while an Interface only defines method signatures

    also, for inheritance i try and look at the "is a" rule

    so base class company
    child class client is a company
    child class supplier is a company

    all these can implement the

    public  interface IIdentifiable{
    int id {get set};
    DateTime LastSave{get;set;}
    }

    which is not to say that interfaces can only be used for "util" purposes...

    Hope this helps you out!

    Tuesday, January 9, 2007 8:57 AM
  • Hi,

    Its difficult to explain the real-time benefits of interfaces, abstract cls etc in such a short span/space. So let me conclude few of the things..

    Interfaces
    - Allows multiple inheritance, extensibility, runtime polymorphism, abstraction/data hiding, easy maintainance/management etc ... long list of benefits but finally all depends on your application requirements....
    e.g if you wish that a Human will have some specific characteristics, some of then can be found in other species and some of them are specific to the human then you can have IHuman (for human specific), ISpecies (common to all species) etc and you can impl these in Human

    So Human implements IHuman, ISpecies

    Now ISpecies can be implemented in Animal class to so this class can be implemented from IAnimal, ISpecies

    In concrete class or abstract class this is not possible. you can inherit from only ONE class while multi interface can be allowed.

    So if you have such requirement then you must use interfaces to reduce repeating code, good maintainability.

    Also lets say if you have created ISpecies and you have derived Human class then its possible that ISpecies can be used in future for Animal class or something like that etc then fur extensibility point of view its good to have it.

    Its basically OOP design concepts why you need to use interfaces.

    If yo have a very small application which has not future extension requirement and straight forward impl then you dont worry about interfaces but in else can you should...

    Also there is another benefit which is already explained in some post for your reply... that if you have two diff objects consiting same method then you can use interface to call that method without worring that which actual object it is.
    e.g. Lets say,
    public void AssignColor (IShape objShape) {
    objShape.Color = "Blue";
    }
    here, lets say IShape has a property named Color and you have a common method to assign color then you dont need to worry that which object is being passed wheter its Square, Triangle or something else.[which impl IShape]
    so AssignColor(objSqare) and AssignColor(objTriangle) both can work without changing your code. Even in future if you add some more shapes using IShape then also this method will work for them also.

    This way LOTS of real-time uses are there but all depends on your application need.

    But this is what i have faced so far that if your project is even a small project, then also its always good to follow OOPs concepts which will give you lots of future benefits.

    May be if you are not much aware/experienced using OOPs designs then it will be difficult to visualize the benefits but the fact is, I always used to use OOPs even in a smallest application. It can give you benefits but if not then also it will never harm you...

    Please find on google about differences between "Interfaces vs. classes" and "Interfaces vs. Abstract classes" etc, and read just top 5-10 links, you will get enough information.

    HTH,

    Tuesday, January 9, 2007 10:42 AM
  • hi,
    i was wondering if you know of any examples similar to the one you describe above with a sorting algorithm or something similar?
    thanks.

    chuckdawit
    Wednesday, February 10, 2010 5:39 AM
  • I am not able to understand what you want to tell. You say that "when we call the Subscribe method of the IPerson class, the .NET framework will call the subscribe method from the objects class". But I don't understand one thing that how does the .NET framework come to know which object it has to call.

    Second thing - Is the basic idea behind using interfaces to have a uniform name of methods in different classes?

    If so, then we can directly name the desired methods with similar names and in this way we can save a lot of source code, can't we?

    One more thing that i want to ask is that - I read somewhere that we can't make any implementation within an abstract class, but i read in some MSDN resource that we can make implementations in it. I don't know what is correct. If the former is true, then what is the use of abstract classes (I have the same argument as in the case interfaces). If the thing given on MSDN is correct then what is the difference between a 'regular' class and an abstract class.

    Please do reply to both of my queries as I get freaked up whenever i read something regarding interfaces and abstract classes.

    Thanx.

    Thursday, October 14, 2010 12:20 PM
  • Well, interfaces are contracts. That means, you are signing a contract with the users of your object, that the object will do so and so tasks. Those who consumes the object will have a clear picture of what he can expect from the object.

    Abstract classes are useful when you want to group logically similar/common functionalities of child implementators.  dog.walk() and cat.walk() are not same but we know both can walk. Then it can be a walk() inside IAnimal interface.

    Male.write() and Female.write() can be similar. Hence it can be a method implementation inside an abstract class.

    My examples could be horrible..but still I hope it might throw some light to what you are looking for.

    Saturday, February 12, 2011 3:28 AM
  • It's too late a reply, that I am not sure if it'll be useful to you anymore. Still..

    >>> 'when we call the Subscribe method of the IPerson class, the .NET framework will call the subscribe method from the objects class'.

    In the example in that post, there were two objects created.

    List<IPerson> myList = new List<IPerson>();
    IPerson person1 = new Customer();
    myList.Add(person1);
    
    IPerson person2 = new Employee();
    myList.Add(person2);

    Here, person1 is an instance of Customer. (In other words, actually an object of type Customer that gets created). The Customer class in turn implements the IPerson interface, which means it has a public method called Subscribe() defined in it. Similarly for person2. However, person2 would be an object of type Employee.

    >>> Is the basic idea behind using interfaces to have a uniform name of methods in different classes?If so, then we can directly name the desired

    >>> methods with similar names and in this way we can save a lot of source code, can't we?

    You could if you so please.

    But taking the same code snippet as above, you cannot maintain a common List that can hold both Employee and Customer (as the myList in the above example does) and call the subscribe method on it, not bothering the implementation of the method (in this case, if it a paid or a free subscription).

    Hope this answers the first part of your question.


    Saturday, June 9, 2012 9:43 AM
  • To answer your question about abstract classes and implementations, it looks like you have confused 'implement' and 'instantiate'.

    Here is a nice post on codeproject.

    Hope it helps.

    Saturday, June 9, 2012 9:46 AM
  • Here, person1 is an instance of Customer. (In other words, actually an object of type Customer that gets created). The Customer class in turn implements the IPerson interface, which means it has a public method called Subscribe() defined in it. Similarly for person2. However, person2 would be an object of type Employee.

    >>> Is the basic idea behind using interfaces to have a uniform name of methods in different classes?If so, then we can directly name the desired

    >>> methods with similar names and in this way we can save a lot of source code, can't we?

    You could if you so please.



    Great answers Sruti i got very clear picture about the interfaces now.

    Thank you so much for the explanation.

    Monday, July 30, 2012 10:29 AM