0

Would I be correct in thinking that an interface has 3 main benefits.

  1. A blueprint to what must be created (I have also heard others refer to it as a contract).
  2. Polymorphism.
  3. Unlike inheritance (which IMO has many similarities) you can have many interfaces

Are there any other plus or minus points and does anyone not agree with my 3 points?

Dave
  • 8,163
  • 11
  • 67
  • 103
  • 1
    Although languages like C# only support the inheritance of a single class (but multiple interfaces) - languages like C++ support multiple inheritance... – Robbie Dee Oct 04 '12 at 12:29
  • Another benefit that it makes possible things that otherwise would not be possible in languages with single inheritance. For example in Java, you can have a class that implements multiple interfaces. But you cannot have a class that has more than one base class. (You can say that this is part of polymorphism.) An interface is also said to be a "specification without implementation" or an "abstract type" (=blueprint). – nagylzs Oct 04 '12 at 12:30
  • @RobbieDee - of course - did you guess I'm from C#! :) – Dave Oct 04 '12 at 12:32
  • 1
    Possible duplicate of [Why would I want to use Interfaces?](http://stackoverflow.com/questions/240152/why-would-i-want-to-use-interfaces), [Interfaces: Why can't I seem to grasp them?](http://stackoverflow.com/questions/122883/interfaces-why-cant-i-seem-to-grasp-them?rq=1), [Why use Interfaces, Multiple Inheritance vs Interfaces, Benefits of Interfaces?](http://stackoverflow.com/questions/8531292/why-use-interfaces-multiple-inheritance-vs-interfaces-benefits-of-interfaces) and [many, many others](https://www.google.nl/search?q=why+use+interfaces). – CodeCaster Oct 04 '12 at 12:33

3 Answers3

1

The "blueprint" metaphor works better for classes than for interfaces, but the "contract" metaphor is pretty accurate. An interface specifies what other classes can expect in terms of public methods, without saying anything about the underlying implementation. Where inheritance between classes tends to consist of is-a relationships, interfaces can be thought of as works-as-a relationships, though I don't think the latter term is in common use.

skunkfrukt
  • 1,550
  • 1
  • 13
  • 22
1

I would add that the use of interfaces goes some way to creating self-documenting code. For example, the interfaces that your class implements describes the functionality the class supports. So, you end up with code that looks like:

if (someClass is ISearchable)
{
   someClass.Search();
}
David Osborne
  • 6,436
  • 1
  • 21
  • 35
1

Two objects with the same Interface do not need to be otherwise related.

So you could have - Flower - Truck - Dinosaur

all having the same interface - IColor

even though they are completely different objects.