-1

Possible Duplicate:
Interfaces: Why can't I seem to grasp them?

to work with a library I just found I need to implement a few interfaces first. But some methods seem to be asking for objects that have the type of some interfaces... And if I have an interface called MyInterface I can write things like :

    MyInterface shoe;

It does not really make sense to me. Can somebody teach me this concept ? I read this : http://www.dotnetperls.com/interface but it did not really help, I think this concept is a bit more complex than what is presented here.

Thanks !

edit :

For those who wonder, I am not new to Interfaces but it is the first time I ran into such a use of them. And for those downgrading my question, I did search but was unlucky apparently.

Community
  • 1
  • 1
Lewis
  • 84
  • 9

6 Answers6

4

A simple explanation: A class is like a company. If it claims to be a sales company, it has to provide sales services. It it claims to be a train factory, it has to be able to make trains. If the national railroads wants to buy trains, it can use any company that can produce trains.

An interface describes what a class has to be able to do. It is like a contract. Each class that wants to have an interface has to fulfill that contract and be able to do what the contract says it has to do. Class instances can perform actions through class methods.

However, the contract doesn't say how the class should do it. So a class can implement the functionality however it wants, or in other words, implement the interface.

public Train
{
    private price;
    public Train(float price) { this.price = price; }
}

public IMyInterface
{
   Train MakeTrain();
}

public ExpensiveTrainFactory : ITrainProducer
{
    // make a luxury, expensive train
    public Train MakeTrain() { return new Train(4000.0); }
}

public CheapTrainFactory : ITrainProducer
{
    // make a cheap train
    public Train MakeTrain() { return new Train(500.0); }
}

public NationalRailways
{
    List<Train> trains;
    public NationalRailways()
    {
        this.trains = new List<Train>();
    }
    public Train BuyTrain(ITrainProducer factory)
    {
        // you can call MakeTrain() because the ITrainProducer guarantees that it can make trains
        trains.Add(factory.MakeTrain());
    }
}

and then in your code:

NationalRailways railway = new NationalRailways();
ExpensiveTrainFactory expFactory = new ExpensiveTrainFactory();
CheapTrainFactory cheapFactory = new CheapTrainFactory();

// expFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer)
railways.BuyTrain(expFactory);
// cheapFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer)  as well
railways.BuyTrain(cheapFactory);
ipavlic
  • 4,906
  • 10
  • 40
  • 77
  • Ehm... that was not my question, I know what an interface is, I'm not new to software development... but thanks anyways – Lewis Aug 03 '12 at 10:08
  • 1
    @Lewis Then I must have misunderstood your question. Would you care to edit your question to make it clearer? – ipavlic Aug 03 '12 at 10:11
  • @Lewis You might have seen interfaces before, but reading through your comments and edits, it seems that you haven't realized that you can program to interfaces. The concepts of programming to interfaces and polymorphism through interfaces really make interfaces useful as a concept. Notice that `BuyTrain` expects what you call a "interface instance" - it actually expects any class that implements a `ITrainProducer` interface. Also notice that `MakeTrain` produces different trains for different classes implementing the `ITrainProducer` interface - either cheap or expensive. – ipavlic Aug 03 '12 at 11:41
  • Yes I understand what you are saying. The thing is I tend to use more abstract classes as most of the time I don't feel the need for interfaces. In the Library I am trying to use I understand why it is used : because you cannot create inheritance with classes that may not fit to your class model logic and more importantly for classes that just don't exist yet and might be completely different but will still use certain funcionalities... declared in your interface. – Lewis Aug 03 '12 at 12:24
  • @Lewis It's also important to note that `struct`s can also implement a interface and unlike class inheritance, one class (or a struct) can implement (inherit from) multiple interfaces. – ipavlic Aug 03 '12 at 12:30
  • Thanks, I know all this... I also know interfaces were created in the begining to solve the OOP problem of multiple inheritance, which interfered violently with polymorphism. – Lewis Aug 03 '12 at 12:41
3

You can declare an Interface, like in your example. However you can not instantiate one.

MyInterface shoe = new MyInterface ();

The above is not legal code. Since an Interface just describes a contract, it has no implementation details, this is left to the client code (you). Therefore it makes no sense to be able to create actual instances of MyInterface.

What you can do, is have a class SomeClass, implement the MyInterface contract:

SomeClass: MyInterface
{
  //implement the methods of MyInterface. All of them, to fulfill the contract.
}

Then you can do things like:

MyInterface shoe = new SomeClass();

Since SomeClass implements the MyInterface contract, the above is legal. You can create an instance of SomeClass because it contains implementation details.

Then you can build on this and create more classes which implement MyInterface.

The beauty of this is that you can have a method for example:

void someMethod (MyInterface test)
{

}

You can pass this method the SomeClass object or any other class you created which implements MyInterface.

Then inside this method, you can call methods that the contract contains without knowing the exact object which has been passed to you. This makes writing future code easier. You can create new objects and so long as they implement MyInterface, it is valid to pass this object to someMethod without changing the declaration of the method.

Science_Fiction
  • 3,403
  • 23
  • 27
  • Thanks ! That is clear enough. This concept makes sense in parallel with the abstract class concept. – Lewis Aug 03 '12 at 10:17
2

You are correct, you can't directly create an instance of an interface. However, you can create an instance of some type that implements that interface.

Say I have an interface

public IMyInterface
{
   void DoSomething();
}

(note: usually you start the name of an interface with "I")

Plus I have a class

public MyClass: IMyInterface
{
    public void DoSomething() { ... }
}

Then I can do

IMyInterface something = new MyClass();

although you often call some (factory) method to return some class that implements that interface instead of directly doing a new.

By using the interface as the type of your variable, you specify that you are only interested in the methods and properties specified there.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • I understand better now... but though I don't see any use for that. thanks =) – Lewis Aug 03 '12 at 10:12
  • 1
    @Lewis a very powerful use for that is called polymorphism: you can have a collection of different objects (e.g. data sources) that have a common interface but are implemented differently (e.g. flat files, XML files and databases) - then you can mix, match and modify them as you like without modifying the classes that use such objects. – Ilmo Euro Aug 03 '12 at 10:26
  • @Lewis - that library accepts parameters of that interface type: that means that any class is accepted, even classes that you write, *as long as they implement that interface*. – Hans Kesting Aug 03 '12 at 10:38
  • @llmo Euro : Thanks for the clarification ! It's just that I tend to use more abstract classes for polymorphism... Unless I need to solve an inheritance logic I don't feel any need for interfaces. – Lewis Aug 03 '12 at 12:16
  • @Hanks Kesting : thanks, many of you mentionned it – Lewis Aug 03 '12 at 12:17
2

In C#, each value has two different types: apparent type and actual type. The apparent type is the type of the variable holding the value, and the actual type comes from the constructor used to create the value. Let's say we have the following class:

class MyClass : BaseClass, IMyInterface {
    /* ... */
}

Then all the following declarations are valid:

object obj1 = new MyClass();
IMyInterface obj2 = new MyClass();
BaseClass obj3 = new MyClass();
MyClass obj4 = new MyClass();

The apparent and actual types are as follows:

object obj1 = new MyClass(); /* apparent: object, actual: MyClass */
IMyInterface obj2 = new MyClass(); /* apparent: IMyInterface, actual: MyClass */
BaseClass obj3 = new MyClass(); /* apparent: BaseClass, actual: MyClass */
MyClass obj4 = new MyClass(); /* apparent: MyClass, actual: MyClass */

When you manipulate an object (call its methods, etc), you do it assuming the object has its apparent type - you can't call any class-specific methods of an object. The apparent type dictates the interface of the object visible outside the object.

What actually happens under the hood is done according to the object's actual type - for example, if you override the ToString method of your class, the overridden method is called in the following code:

object obj = new MyClass();
Console.WriteLine(obj.ToString());

The actual type dictates how the object's functionality is implemented.

Ilmo Euro
  • 4,925
  • 1
  • 27
  • 29
1

Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me use same example as per your link with bit of modification:

using System;

interface IPerl
{
    void Read();
}

class Test : IPerl
{
    public void Read()
    {
    Console.WriteLine("Read Test");
    }
}

class Test1 : IPerl
{
    public void Read()
    {
    Console.WriteLine("Read Test1");
    }
}

class Program
{
    static void Main()
    {
    IPerl perl = new Test(); // Create instance of Test.
    perl.Read(); // Call method on interface output will be different then Test1.

        perl = new Test1(); // Create instance of Test1.
    perl.Read(); // Call method on interface output will be different then Test.

    }
}

Output:

  1. "Read Test"
  2. "Read Test1"

I hope this would help.

Thanks Ankur

Ankur Ghelani
  • 659
  • 4
  • 16
0

What Interfaces Are

Interfaces basically define a blueprint for a class or a struct. The programmed definition of an interface looks very similar to a class, but nothing is implemented. Interfaces define the properties, methods, events, and indexers, but the interface does not define the implementation of any of these. It just declares their existence. Interfaces will not actually define any functionality. They just define ways in which interactions with a class takes place.

What Interfaces Are Not

Interfaces should not be confused with inheritance. They are two very different things. Inheritance will define a lot of the implementation and is used for code reuse. Interfaces are merely a definition for how communication with the implementing classes must take place. It is like a written contract. A class "signing" the contract will agree to perform certain specified actions in any way it wishes, but it must perform the specified actions.

When to Use Interfaces

Interfaces allow us to create nice layouts for what a class is going to implement. Because of the guarantee the interface gives us, when many components use the same interface it allows us to easily interchange one component for another which is using the same interface. Dynamic programs begin to form easily from this.

For more information visit this post about Understanding_Interfaces_in_C#

Jonas W
  • 3,200
  • 1
  • 31
  • 44
  • 1
    The [site guidelines strongly discourage](http://stackoverflow.com/questions/how-to-answer/) posting only links without describing the most important part of their contents. – O. R. Mapper Aug 03 '12 at 10:01
  • @O.R.Mapper I'm sorry about this. I've updated my post now. Thanks for informing me about this. – Jonas W Aug 03 '12 at 11:07
  • I am familiar with interfaces already, I just suprisingly did not ran into this use of it. I am very sorry if my question was unclear. – Lewis Aug 03 '12 at 13:47