Software interfaces in object-oriented languages

In object-oriented languages, the term interface is often used to define an abstract type that contains no data or code, but defines behaviors as method signatures. A class having code and data for all the methods corresponding to that interface is said to implement that interface. Furthermore, a class can implement multiple interfaces, and hence can be of different types at the same time.

An interface is thus a type definition; anywhere an object can be exchanged (for example, in a function or method call) the type of the object to be exchanged can be defined in terms of its interface rather than specifying a particular class. This approach means that any class that implements that interface can be used. For example, a dummy implementation may be used to allow development to progress before the final implementation is available. In another case, a fake or mock implementation may be substituted during testing. Such stub implementations are replaced by real code later in the development process.

Usually a method defined in an interface contains no code and thus cannot itself be called; it must be implemented by non-abstract code to be run when it is invoked. An interface called "Stack" might define two methods: push() and pop(). It can be implemented in different ways, for example, FastStack and GenericStack—the first being fast, 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.

Though interfaces can contain many methods they may contain only one or even none at all. For example, the Java language defines the interface Readable that has the single read() method; various implementations are used for different purposes, including BufferedReader, FileReader, InputStreamReader, PipedReader, and StringReader. Marker interfaces like Serializable contain no methods at all and serve to provide run-time information to generic processing using Reflection

Programming to the interface

The use of interfaces allows for a programming style called programming to the interface. The idea behind this approach 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.

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.


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



double arrow
Сейчас читают про: