views:

509

answers:

11

Hi All,

I would like to know the significant use of Interface. I have read many articles but not getting clearly the concept of interface.

I have written a small program. I have defined the Interface Itest.Class(Manager) has implemented the Interface.Another class(Employee) has not implemented interface. But defined the same method(DoSomething()) in the interface in the class(Employee). I can call the method from the class object. Then why should i go and implement interface. I can directly implement the method in a class and call the method. Why should i go for extra step of implementing method in a Interface and then inheriting the interface by class. I know interface supports multiple inheritance, but I am not using multiple inheritance in this example.

Thanks for any ideas or input.

public interface Itest
{
    void DoSomething();
}

public class Manager:Itest
{
    public void DoSomething()
    {
        Console.WriteLine("test....");
    }

}
class Employee
{
    public void DoSomething()
    {
        Console.WriteLine("test....");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Manager m = new Manager();
        m.DoSomething();
        Employee e = new Employee();
        e.DoSomething();
        Console.ReadLine();
    }
}
A: 

Of course you can implement the method declared in the interface without implementing the interface. Simple put, interfaces just make sure you don't forget about it (they will give you compile errors if any of the interface members in not implemented).

RaYell
Same is true of abstract methods in an abstract base class.
Daniel Earwicker
Yes that's true. The difference is that interface gives only the the description of method when abstract class can have a code that does something.
RaYell
The abstract methods in the abstract class (see my first comment) only give the description of the method, exactly like methods in an interface. The only capability unique to interfaces is multiple inheritance.
Daniel Earwicker
+8  A: 

Interfaces are used for abstraction (abstract classes are also used for this, but normally contain some implementation that is intended for reuse).

In C# they allow the use of multiple inheritance, meaning you can implement many different interfaces in one class.

If you have many different implementations of an interface, you can substitute them for one another, so long as you use the interface declaration.

For example:

IAnimal can be implemented by Cat and by Dog. In other code, you want to call the Talk method that is declared in the interface. Your code does not have to care whether it is a Cat object or a Dog object. You can add a Duck or a Human and not change that piece of code.

This is also useful when testing your code with mock objects, so a simple object can be substituted for the real one for testing purposes.

Some interfaces are used as markers so reflection can pick them up easily (on example is the ISerializable interface, marking a class as serializable).

Oded
"Interfaces are used for abstraction" - so are abstract classes/methods, hence the name.
Daniel Earwicker
An interface is the most abstract concept that there exist in OO programming. Abstract classes are more concrete than interfaces and usually implement some interfaces. What matters is the concept, not how a specific language call a concept.
Trap
+1 for mentioning testing, which is my main reason for using interfaces - so I don't need any real data in a database to perform testing - I just run up a mock using Moq (and others do the same with Rhino, NMock2 et al).
Sohnee
+1. Interfaces are a powerfull design tool.
Frank
+11  A: 

Interfaces allow you to sort of use multiple inheritance. In your example, it woulda allow you to put an instance of Employee or Manager into the same variable, and then call DoSomething on that variable, with the method call being dispatched to the instance that is currently referenced by that variable. For example:

public interface IEmployee {
    void DoSomething();
}
// assume Manager and Employee both implement IEmployee

IEmployee ie = new Manager();
ie.DoSomething();    // calls Manager.DoSomething()
ie = new Employee();
ie.DoSomething();    // calls Employee.DoSomething()

If you didn't use interfaces, you would have to do:

object o;

// assign Manager or Employee (or something else!) to o

if (o is Manager)
    ((Manager)o).DoSomething();
else if (o is Employee)
    ((Employee)o).DoSomething();

An interface defines a contract, and as long as an instance implements that interface you don't care what it actually is at runtime. You can have the same class implement multiple interfaces, and then use instances of that class in all variables of those interfaces. You couldn't use the same for abstract classes, as a class can only inherit off one class at a time.

One example where I'm using interfaces now is to define an object model - I've got interfaces for various properties (IHasStorage, IHasPrivileges, IHasCheezburger), then the classes representing the concrete objects implement whichever and however many interfaces are appropriate for that class' properties

thecoop
+1 because support for MI is the *unique* value of interfaces (compared with abstract classes/methods).
Daniel Earwicker
And, to amplify, your second code fragment *still* wouldn't do the job because it couldn't handle things-that-could-do-DoSomething that weren't anticipated by the calling routine's author. If I later introduce a Contractor class, the interface-based approach just keeps on rollin', but the `if (o is X)` routine has to be updated to handle the new case.
itowlson
The owner of the instantiated class should store it as the most derived type, i.e. "Manager m = new Manager();". Otherwise you will erase all other properties which might be important. e.g. if Manager implements IDisposable. Non-owning methods should use the least derived type needed.
adrianm
@adrianm: huh? You should generally use as non-specific a type as possible. Referring to an instance of a specific type by a less specific type doesn't "erase" the other properties, it just limits what the calling code is allowed to do with the object - which is kind of the point.
Iain Galloway
@adrianm: That's simply an example of using an interface to call a method :)
thecoop
+1  A: 

The inheritance of interface give you the possibility to change your implementation with other class or object without breaking your code. The Interface means that you make a contract with the clients of your code that you will provide some functionality and they don't have to know which particular class to call for this. The Interface adds a layer of abstraction, so your the clients of your code will not depend on how your implement the solution. They just know that you will provide them, what is in the interface.

anthares
This is true of abstract classes - except with interfaces it is *worse*. If you add a method to an abstract class, you can provide a default implementation. If you try the same with an interface, you break all the libraries that implement it.
Daniel Earwicker
Abstract classes have different purposes. To code some behavior that is common for hierarchy and to avoid code duplication.
anthares
+1  A: 

A very good analogy for interfaces is provided Matthew Cochran

"This make for a much easier "code world" in which to navigate. Imagine if instead of learning how to drive a car and then being able to drive any car, we had to learn how to drive each instance of every car we get into. It would be really inefficient if after learning how to drive the Ford Pinto we had to start all over again in order to figure out the Mustang. A much more efficient way is to deal with the cars interface: the steering wheel, turn signals, gas pedal and brake. This way, no matter what is implemented on the backend of the interface, we don't really care because in the end it subscribes to the basic car contract and that is how we will deal with it (through the interface).2

Along with the general explanation above, most of the modern Software Design pattern, very much rely on interfaces such as Dependendency Injection

Consider this example:

You have a class that is capable of playing media files(mp3). You give that class to you friend who tries to play MPEG type of files. It would not be possible for him to do so without making significant changes to you class.

public class MusicPlayer 
    {
       void Play(Mp3 _mp3File){}
    }

consider this

Instead of passing type of mp3 file to Play Method what if you pass this Method, a derived from an interface of Type MediaType.

    public interface MediaType { }

    public class Mp3 : MediaType
    { }

    public class MPEG : MediaType
    { }

and class:

    public class MusicPlayer 
    {
       void Play(MediaType _mediaFile){}
    }

In this scenario, you can derive another MediaFile type and from MediaType like MPEG and pass that to the Play Method and it will happily accept it and play it for you(provided logic).

   public class TestPlayers
    {
        public void PlayMedia()
        {
            MusicPlayer musicPlayer = new MusicPlayer();
            musicPlayer.Play(new Mp3());
            musicPlayer.Play(new MPEG());
        }       
    }

Hope this helps

Asad Butt
All of the above is equally true of abstract classes.
Daniel Earwicker
Earwicker: Are u sure we can do the above with abstract class.Do you have any examples or links...
Shikha
+1  A: 

Hi, interfaces are useful in a bit more complex scenarios, e.g.

(1) You need multiple inheritance (in c# you can't inherit from 2 classes), e.g. you have interfaces IProduct, IDisposable. Not every product needs to be disposed, so it doesn't make sense to implement it on all products, etc.

(2) When you use dependency injection (inversion of control) and a mocking framework (e.g. RhinoMocks) for you unit testing - then you have to work with interfaces, otherwise your mocking framework is not going to work.

Grzenio
If i am not using MI, Interface has no use?
Shikha
+1  A: 

You know, funny enough that I was just talking to one of our developers at work about this very topic today.

The easiest way for me to explain what an interface and it's usability is, is the following example.

interface IGraphicsRenderer
{
     Render(List<Triangle> triangles);
}

Then you might have 2 types of rendering engines, Direct3D or OpenGL

class Direct3DRenderer : IGraphicsRenderer
{
   public void Render(List<Triangle> triangles);
}

class OpenGLRenderer: IGraphicsRenderer
{
   public void Render(List<Triangle> triangles);
}

To show it's usefulness, you might have something along the lines of

IGraphicsRenderer renderer = new Direct3DRenderer();
renderer.Render(foo);

to change the renderer, all you need to do is change the initialization.

IGraphicsRenderer renderer = new OpenGLRenderer();
PieterG
+2  A: 

When You have too many class which drive from an Interface classyou ensure that all of them implement a Method.

Then if your Interface changes (e.g:

       public Interface IAnimal
            {
                public void Talk();
                public void Eat();
            }

and then you add another method

       public Interface IAnimal
            {
                public void Talk();
                public void Sleep();
                public void Eat();
            }

then you can ensure which all of them will implement the Sleep() method. if you have too many classes which dervice from IAnimal Inteface then youhave to implement Sleep() for all of them. this help you extend as easy as possible your derived classes

Nasser Hadjloo
A: 

I assume you want a very simple answer.

There are 2 types of inheritance:

  • TYPE 1: interface inheritance (in simple terms: when the outside of the class is inherited)
  • TYPE 2: implementation inheritance (when the inside of the class is inherited)

If you write

class MyClass : Base {}

you are using BOTH type 1 and 2. But if you implement an interface that's clear type 1.

Type 1 is for polymorphic use and type 2 is for code reuse.

So the bottom line is if you want to use polymorphism but you

  • don't want to provide any implementation
  • or simply can't do it. Mostly in case of multiple inheritance - note: c++ allows it, it follows another philosophy

interfaces are for you :)

There are another uses(e.g. force the implementation of a method) but in my opinion this is the point.

naeron84
A: 

Interfaces are for designs. The actual implementation follows what is defined in the design (read interface). The concept of interface gives one the flexibility to design a system without going into the details of the implementation, or keeping the design extensible by implementing the interfaces in the future. This is also known as abstraction.

While interface gives flexibility at the time of designing, it puts the constraint at the time of implementation. Any implementation of an interface need to be complete, means one need to implement all the specifications defined in the interface at the time of implementation. Also the other flexibility at this time is that one can implement multiple interfaces in one class.

This is a very strong concept that provides a very high degree of flexibility at the time of design and making sure that the implementation will not break the design.

Kangkan
+3  A: 

Implementation inheritance models an "IS A KIND OF" relationship, whilst interface inheritance models a "CAN BEHAVE LIKE" relationship. It's no coincidence that many of the BCL interface names end with "-able", representing the ability to do something. To demonstrate, image the following code:

class Person
{
  public string Name{get;set;}
  public void Walk() {/*code elided*/}
}

class Employee : Person
{
  public int Id{get;private set;}
}

Clearly, an Employee "is a kind of" Person. All employees are people, therefore they all have a Name and can Walk(). By all means make Person or Employee abstract, it doesn't change the fact that all employees are people.

Now let's get a bit more abstract and talk about the concept of being a vehicle. The absolute essential for a thing to be a vehicle is that it must be able to move and stop. You might include steering and carrying passengers but I'm keeping it very abstract.

Let's think about some things that are vehicles. A car, of course, but how about a person? They can move and stop (and when I give my nephews and nieces piggy-backs I'm carrying passengers too!) A wheely chair? I'm forever davrossing around the office. I'm a keen sailor too, and use the wind to accelerate and decelerate my vehicle.

You can't model this kind of a relationship using implementation inheritance, because you have lots of different things that "can act like" a vehicle but don't neccessarily inherit from the same base class.

A pogostick (with apologies to professional pogo-ers) IS A KIND OF Toy, but CAN ACT AS a vehicle. Not all toys are vehicles. A Person has no relationship to a Car, other than the fact that it CAN ACT AS a vehicle.

interface IVehicle
{
  void Move();
  void Stop();
}

class Toy{}

class PogoStick : Toy, IVehicle
{
  public void Move(){ /* boing boing */}
  public void Stop(){ /* fall over */}
}

class Car: IVehicle
{
  public void Move(){ /* vroom vroom */}
  public void Stop(){ /* <screeeech!> */}
}

class Person : IVehicle
{
  public string Name{get;set;}
  public void Walk() {/*code elided*/}
  void IVehicle.Move() { Walk(); }
  void IVehicle.Stop() { /*whatever!*/}
}

class Program
{
  static void Main()
  {
    IVehicle[] vehicles = new IVehicle[3];
    vehicles[0] = new PogoStick();
    vehicles[1] = new Car();
    vehicles[2] = new Employee(); //implements IVehicle because it IS A KIND OF Person

    vehicles.ForEach(v => v.Move());

    //it's worth pointing out that
    vehicles[2].Stop();
    //works fine, but
    Person p = new Person();
    p.Move();
    //won't, as I explicitly implemented the interface, meaning I can only get at the
    //methods via a reference to the interface, not to the implementing class.
  }
}

To use an example from .NET itself, what on Earth does a string have in common with a List? Not a lot, except that I can "foreach" both of them:

class Demo
{
  static void Main()
  {
    string s = "Hello!";
    List<Employee> payroll = new List<Employee>();

    for each (var item in s)
    {
      Console.WriteLine(item);
    }

    for each (var item in payroll)
    {
      Console.WriteLine(item);
    }
}

The common base class for string and List is object, but not all objects are "for-each-able", so there has to be something else going on. Namely that they both implement the IEnumerable interface (there's that -able!)

Daniel Ives