Tuesday, July 27, 2010

Interface

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. Furthermore, a class can implement multiple interfaces, and hence can be of different types at the same time.

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.

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.
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. Some languages (like C#) also permit the definition to include properties owned by the object, which are treated as methods with syntactic suga