Main article: Protocol (object-oriented programming)
In object-oriented languages, the term "interface" is often used to define an abstract type that contains no data, but exposes behaviors defined as methods. A class having all the methods corresponding to that interface is said to implement that interface.[3] Furthermore, a class can implement multiple interfaces, and hence can be of different types at the same time.[4]
An interface is hence a type definition; anywhere an object can be exchanged (in a function or method call) the type of the object to be exchanged can be defined in terms of an interface instead of a specific class. This allows later code to use the same function exchanging different object types; hence such code turns out to be more generic and reusable.[citation needed]
Usually a method in an interface cannot be used directly; there must be a class implementing that object to be used for the method invocation. For example, one can define an interface called "Stack" that has two methods: push()
and pop()
and later implement it in two different versions, say, FastStack and GenericStack—the first being faster, but working with a stack of fixed size, and the second using a data structure that can be resized, but at the cost of somewhat lower speed.
This approach can be pushed to the limit of defining interfaces with a single method; e.g. the Java language defines the interface Readable that has the single read()
method and a collection of implementations to be used for different purposes, among others: BufferedReader, FileReader, InputStreamReader, PipedReader, and StringReader; or even less, marker interfaces like Serializable contain virtually nothing.[5]
In its purest form, an interface (like in Java) must include only method definitions and constant values that make up part of the static interface of a type. The C# language also permits the definition to include properties owned by the object, which are treated as methods with syntactic sugar, but no constants (in contrast to Java), constructors, destructors, fields, nested types, or operators.[6]
The use of interfaces allows a programming style called programming to the interface. The idea behind this is to base programming logic on the interfaces of the objects used, rather than on internal implementation details. Programming to the interface reduces dependency on implementation specifics and makes code more reusable.[7] It gives the programmer the ability to later change the behavior of the system by simply swapping the object used with another implementing the same interface.
Pushing this idea to the extreme, inversion of control leaves the context to inject the code with the specific implementations of the interface that will be used to perform the work.
http://en.wikipedia.org/wiki/Interface_%28computer_science%29