Software interfaces in object-oriented languages

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 exposesbehaviors defined as methods. 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.

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 interfaceReadable that has the single read() method and a collection of implementations to be used for different purposes, among others:BufferedReaderFileReaderInputStreamReaderPipedReader, and StringReader; or even less, marker interfaces like Serializablecontain 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 thestatic 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]

posted on 2013-03-27 01:49  Step-BY-Step  阅读(144)  评论(0编辑  收藏  举报

导航