81

Why do we use Interface?

Is it only for Standardization?

davidweitzenfeld
  • 1,021
  • 2
  • 15
  • 38
Azhar
  • 20,500
  • 38
  • 146
  • 211
  • 1
    as opposed to...? interfaces have many uses... – Jason Jan 08 '10 at 07:22
  • 6
    I really wish that people wouldn't put tags like c# on posts that aren't c# specific. Its a really great question, and I might have missed it because c# is an ignored tag. – Tyler Carter Jan 25 '10 at 17:52

12 Answers12

174

Purposes of Interfaces

  • create loosely coupled software
  • support design by contract (an implementor must provide the entire interface)
  • allow for pluggable software
  • allow different objects to interact easily
  • hide implementation details of classes from each other
  • facilitate reuse of software

Analogy 1: Much like the US space shuttle, Russian Soyuz spacecraft and Chinese Shenzhou 5 can all dock to the International Space Station, because they implement the same docking interface. (This is just an example - I don't know if it's true in real life however let's suspend our disbelief for the sake of an example)

Analogy 2: Like you can plug various computer monitors into your home computer. You can plug a wall-size TV into it, an old CRT (the thick kind), a 20" flat screen, or a braille machine for the blind to "see" by touch. There's compatibility among these various/different devices and your computer because they all agree on interface standards.

Details of C# interfaces -- With C#/OOP interfaces you're doing the same kind of thing but in the unseen/virtual world.

You're correct about standardization, but also flexibility, scalability, extensibility, maintainability, reusability, testability and power.

(The more you use software interfaces the more these "buzz words" will be understood. And always consider interfaces in the real world because they have done us equally well.)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
John K
  • 28,441
  • 31
  • 139
  • 229
  • 18
    You left out my favorite use of interfaces: testability. If I have two classes, A & B, and A.foo calls B.bar, then as long as B implements an interface and can be "injected" into A, then I can use a mock, fake, or stub class instead of the real B. This is especially useful when A.foo changes its behavior based on the return value from B.bar. (Say B.bar returns a bool. A.foo might have an if(B.bar) statement with an else clause.) Using an interface in B allows me to create mockB, fakeB and/or stubB which allow me to test what happens when B.bar returns true or false. – aridlehoover Jan 24 '10 at 10:05
  • @Alan R -testability added. Thanks. – John K Jan 24 '10 at 22:54
  • 6
    +1 for `standardization, but also flexibility, scalability, extensibility, maintainability, reusability, testability and power.` – Ravi Nov 30 '12 at 10:08
  • 1
    Accepted answer is TOP stuff and it's refreshing to see the concept not discarded as most framework design guidelines materials fail to explain or understand it. Just adding that if you are using Generics seriously, I don't know how you ever got by without them. – rama-jka toti Jan 24 '10 at 22:57
30

An interface is used to describe what an implemented thing can do. So you have the possibility to treat several objects which implementing the same interface as a type of this interface.

For example:

public interface IMyInterface{
    public void DoFirst();
    public int DoSecond();
}


public class A : IMyInterface{
   //class has to implement DoFirst and DoSecond
   public void DoFirst(){
     Console.WriteLine("Blubb1");  
   }

   public int DoSecond(){
     Console.WriteLine("Blubb2");
     return 2;  
   }
}

public class B : IMyInterface{
   //class has to implement DoFirst and DoSecond
   public void DoFirst(){
     Console.WriteLine("Blibb1");  
   }

   public int DoSecond(){
     Console.WriteLine("Blibb2");  
     return 4;
   }
}

The classes implement the Interface in several ways. But you can use them as IMyInterface. For example:

public static void DoMethodsInInterface(IMyInterface inter){
    inter.DoFirst();
    inter.DoSecond();
}


public static void main(){

   DoMethodsInInterface(new A());
   DoMethodsInInterface(new B());
   //Or use it in a List
   List<IMyInterface> interlist = new List<IMyInterface>();
   interlist.Add(new A());
   interlist.Add(new B());
   foreach(IMyInterface inter in interlist){
      inter.DoFirst();
   }

}

I hope this makes a bit clear why interfaces are useful.

martin
  • 2,957
  • 3
  • 25
  • 46
  • 2
    This question was linked from a question that asks why to use interfaces rather than simply having members which perform the appropriate functions, etc. and your answer comes closest to answering that one. If two unrelated classes both have a method `Woozle`, any code which wanted to accept a reference to either class and `Woozle` it would have to know which class it was dealing with, and would only be able to `Woozle` classes it knew about. By contrast, if both classes implement `IWoozler`, then code which is given any `IWoozler` can `Woozle` it without having to know its exact type. – supercat May 27 '14 at 21:33
  • This answer nails it better than any I've seen. It's all about what an object can do. Interfaces specify a set of actions related to the object without dictating what happens within those actions which would obviously be object specific. – m12lrpv Mar 30 '17 at 01:03
5

It's for interfacing :), so that you could interface between stuff, it's useful when you have

  • multiple implementations of same stuff
  • when you apply an interface to multiple different classes because you need some sort of convention that these classes are goonna be able to do some stuff or have some functionality
Omu
  • 69,856
  • 92
  • 277
  • 407
4

Here's the high level view...

Interfaces play a big role in the concept of Information Hiding.

They basically help you hide the implementation details of your class so that a calling class does has no dependency on that implementation. Therefore, by using interfaces you can modify the implementation without changing the calling class. This all in turns limits the complexity of your code and make it easier to maintain in the long run.

When I first started understanding interfaces they were explained to me as a "contract that provides a description your class." Not sure if that will help you but if you think of an interface for a car you could say that it drives, breaks, and turns. So as long as it gets me from point A to point B, I don't really have to know how those functions are implemented.

matt_dev
  • 5,176
  • 5
  • 33
  • 44
2

The main reason the interfaces are used in languages like C#/Java is because those languages don't support multiple (class) inheritance (see What is the exact problem with multiple inheritance?).

But multiple (interface) implementation is permited allowing classes to be used in diferent ways.

Community
  • 1
  • 1
Catalin DICU
  • 4,610
  • 5
  • 34
  • 47
  • 1
    Interfaces in managed languages are NOT a replacement for multiple inheritance. And, even in languages that support multiple inheritance, the concept of an interface sans implementation is relavant and useful. (See dependency injection.) – aridlehoover Jan 24 '10 at 10:07
  • 1
    -1 not very well thought-out, or do you really not understand C# or Java? – John Saunders Aug 10 '10 at 06:45
  • All I want to say is that in C++ pure abstract classes can be used instead of interfaces. Most of the things you can do in Java/C# with interfaces you can do in C++ with pure abstract classes. In C++ if you wanted a class to have multiple behaviors you’d inherit multiple pure abstract classes. But you can’t do that in Java/C#. I’m not saying interfaces aren’t "useful", I’m saying more than that: languages like Java & C# wouldn’t really be object oriented programming languages without the multiple interface inheritance. (they don’t allow multiple class inheritance nor mixins) – Catalin DICU Aug 10 '10 at 10:57
  • 1
    +1 This is essentially what has been discovered the hard way by the experience of C# and Java. If you try to simplify by avoiding multiple inheritance, you just create complexity elsewhere. Due to the lack of a unifying underlying approach, you end up with worse complexity. See Krzystof Cwalina's annotation in *C# Programming Language 3rd Edition*, 1.9 Interfaces, which says exactly this. As of now, there are still unsolved problems in C# and Java that would have simple solutions if multiple inheritance of classes was allowed. – Daniel Earwicker Aug 11 '10 at 09:47
  • -1 inheritance and interfaces are really very different. – kenny Aug 13 '10 at 20:02
  • Catalin: I suggest re-wording your answer. :) – Arafangion Aug 15 '10 at 04:09
  • @DanielEarwicker: Is there any way to define semantics for full-fledged multiple inheritance in such a way that class type variables encapsulate nothing but the identity of their target, and casting any class-type variable to `Object` and back will result in a reference to the original target? Such things are possible with multiply-inherited interfaces, but not with any semantics I'm aware of for multiply-inherited classes. – supercat Apr 18 '13 at 21:33
  • @supercat - if you imagine writing an interface for every class, and then only using the interfaces as your variable types, does that do the trick? – Daniel Earwicker Apr 18 '13 at 23:07
  • @DanielEarwicker: Interfaces avoid the problems associated with MI because nothing a derived interface can add to its base type will conflict with anything else a different derived interface can add. Interfaces that inherit other interfaces cannot add method overrides for them; a class implementing the composite interface will provide one method which will be used to implement the method in all interfaces. By contrast, classes that inherit from a common class can add conflicting overrides for the same inherited method. – supercat Apr 18 '13 at 23:20
  • @supercat - Or to put it another way, interfaces lack the *feature* of being able to supply definitions. It's only a problem where there are conflicts, and can be solved by providing a way to explicitly resolve the conflict. Seems like a separate topic from your previous question? – Daniel Earwicker Apr 19 '13 at 09:07
  • @DanielEarwicker: All the ways I know of resolving such conflicts violate the concept of identity-preserving typecasts. Assume X:B, Y:B, and Z:X,Y, and B, X, and Y define or override M(). ((X)someZ).M and ((Y)someZ).M pose no ambiguity, but the rules of inheritance would suggest that ((B)(X)someZ).M should behave the same as ((X)someZ).M; likewise ((B)(Y)someZ).M and ((Y)someZ).M. But unless ((X)someZ).M and ((Y)someZ).M are required to be identical, ((B)(X)someZ).M and ((B)(Y)someZ).M would have to encapsulate something besides the identity of someZ. – supercat Apr 19 '13 at 15:03
  • @DanielEarwicker: In "conventional" C++, inheritance is validated at link time, before an executable is shipped; if an upgraded version of a class has a conflict not present in an older one, it will be caught at that point. In modern frameworks, however, it is common for classes to inherit from classes that are stored in other assemblies (and come from other vendors), so "linkage" doesn't occur until run-time (long after the code has shipped). Code may be unambiguous given the combination of assemblies used in testing, but become ambiguous if an assembly from another vendor gets updated. – supercat Apr 19 '13 at 15:09
2

Interfaces are somewhat awkward. They support design by contract just by believing, that same name and implemented interface means the same behaviour. This works only thanks to API documentation, it has to be human-checked. That makes interfaces too weak. One way to get around that could be formal specs. On the other hand, interfaces are too strong, too strict. You cannot evolve interfaces which often gets in the way of reuse. This is solved by protocols - mechanism in dynamic languages, which send messages(call methods) and when that message is not supported by receiver, standard callback gets called. Having concrete protocols with constraints would be imho better.

Gabriel Ščerbák
  • 18,240
  • 8
  • 37
  • 52
1

Think remoting...

There is a client and a server involved here. Lets say they are physically separated by the internet. The client is calling a method whose actual execution happens on the server. From the client's perspective the client doesn't know anything about the object in the server which performs the execution. However it knows what method to call. Because while building the client program, we are only exposed to an interface (or contract). We are not exposed to the whole object which is actually living on the server. Try doing some demo apps in .net remoting, and you'll figure the rest. Happy programming.

deostroll
  • 11,661
  • 21
  • 90
  • 161
0

Interface separates the data type from the implementation logic.

Anand
  • 1
0

Why do we use interfaces?

Some languages implement polymorphic method calls using vtables and discard most of the type information making it hard not to define interfaces.

So sometime we simply use interfaces because the language design requires it.

Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67
0

Interface provide prototype modal that just contains declaration of functionality of a specific behavior.

and if u want to implement this behavior into class then u must implement this interface in class then class have this behavior functionality or it can have multiple behavior.

because class can implement multiple interface.

Manoj Gupta
  • 456
  • 4
  • 9
0

If anyone else is like me and learns by example and doing, rather than only explanation, here is some code....

I found this implementation of a Neural Network in C#, including project download, which makes use of Interfaces in an elegant and useful manner:

http://www.c-sharpcorner.com/UploadFile/rmcochran/AI_OOP_NeuralNet06192006090112AM/AI_OOP_NeuralNet.aspx

Dave
  • 4,949
  • 6
  • 50
  • 73
0

By starting with an interface, you can implement a proxy, thus allowing for lazy loading or performing some verifications when calling the methods of a concrete implementation.

lmsasu
  • 7,459
  • 18
  • 79
  • 113