سؤال

I already know the fundamentals of the implements and interfaces. I don't understand when to use an interface. What is the requirement to have an interface?

Example:

/// Interface demo
Interface IDemo
{
    // Function prototype
    public void Show();
}

// First class using the interface
Class MyClass1 : IDemo
{
public void Show()
{
    // Function body comes here
    Response.Write("I'm in MyClass");
}
}

// Second class using the interface
Class MyClass2 : IDemo
{
public void Show()
{
    // Function body comes here
    Response.Write("I'm in MyClass2");
    Response.Write("So, what?");
}
}

These two classes have the same function name with different bodies. This can also be achieved without interfaces. What's the purpose of having the method reference? When I extend a superclass, at least I get the superclass's properties and methods.

Please give me a clear explaining and a real world scenario for me to understand well.

هل كانت مفيدة؟

المحلول

First they provide a contract for users, so a user doesn't need to know what underlying implementation is used but rather just the contract. This creates loose coupling in case underlying implementation changes.

Real World Examples

In this manner we can use certain patterns like strategy and command pattern: Using a strategy pattern and a command pattern

Real World Example of the Strategy Pattern

Real world example of application of the command pattern

Difference Between Abstract Class and Interface

Much of this can be said about abstract classes, see here for the differences: Interface vs Abstract Class (general OO)

نصائح أخرى

You need an interface if you need multiple inheritance.

Suppose you have a class that needs to be Comparable and also a List. Since you can only inherit one class in some languages, in order to prove to the compiler that it has both Comparable's compareTo() method as well as List's add() method, you need interfaces. That's the very simplest explanation but I'm sure others will give more reasons.

Also interfaces make multiple inheritance easier in some cases since there is nothing going on "in the background." they only specify what an object needs to offer in terms of methods.

Two reasons to use interfaces:

  1. You need multiple inheritance, and your programming language does not support it (e.g., Java, C#). In this case, most (all but one) of the base classes you inherit in your derived class will need to be defined as interface classes.

  2. You expect to use multiple implementations of a certain class. In this cases, the class can be an abstract class or an interface. Your client provides a specific concrete implementation of this class, which can vary from client to client. The interface (or abstract class) requires the same behavior (methods) for each implementation.

I believe one of the most inportant reasons for using interfaces is type matching. Your programe can be much more flixible by programming to an interface instead of an implementation.

You could take a look at different design patterns (I suggest you start with Strategy Pattern, http://en.wikipedia.org/wiki/Strategy_pattern#Example) I reckon you will instantly understand how program to interfaces makes your code more flexible.

Hope this can help.

Much of the power comes from the fact that an object can be referenced by a variable of the interface type. This is subtly vary powerful.

private foo()
{
     IDemo demoOne = new MyClass1();
     IDemo demoTwo = new MyClass2();
}

This can become vary powerful because you can encapsulate different behaviors. For example:

private foo(bool option)
{
     IDemo demo = option ? new MyClass1() : new MyClass2();
}

private bar (IDemo demo)
{
     demo.Show();
}

Now bar can use the IDemo object without having to know which concrete implementation of IDemo is passed in. The decision about which implementation to use is encapsulated in the foo method. This might not seem like a big deal in such a simple example. If you look at the links posted in tigger's answer, you will see where this can become very useful.

One case where this is particularly useful is with unit testing. You can have a business logic class that takes an interface to a data layer object. When the application runs, the business logic class is passed an instance of the real data layer object. When the class is unit tested, it is passed an instance of a object that returns test data. This allows the unit test to run with predictable data inputs. This is known at Dependency Injection.

Another useful case is when you want to interact with framework or third-party code. Let's say you want to implement a custom collection. If your class implements the IEnumerable interface, you can iterate through the items in the collection in a foreach loop. The framework doesn't need to know how your class stores the items or what is in the items, but if it knows that you implemented IEnumerable, it can allow you to use a foreach loop.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top