Jump to content

Interface (object-oriented programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by AnomieBOT (talk | contribs) at 08:40, 16 November 2022 (Dating maintenance tags: {{Clarify}}). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In object-oriented programming, a protocol or interface type[a] is a data type describing a set of method signatures, the implementations of which may be provided by multiple classes that are otherwise not necessarily related to each other.[1] A class which provides the methods listed in an interface is said to implement that interface.[1]

If objects are fully encapsulated then the protocol is the only way in which they may be accessed by other objects. For example, in Java, the Comparable interface specifies a method compareTo() which implementing classes must implement. This means that a sorting method, for example, can sort a collection of any objects of types which implement the Comparable interface, without having to know anything about the inner nature of the class (except that two of these objects can be compared by means of compareTo()).

Some programming languages provide explicit language support for protocols (Ada, C#, D, Dart, Delphi, Go, Java, Logtalk, Object Pascal, Objective-C, OCaml, PHP, Racket, Seed7, Swift). In languages supporting multiple inheritance, such as C++, interfaces are implemented as abstract classes.

In languages without explicit support, protocols are often still present as conventions. This is known as duck typing. For example, in Python, any class can implement an __iter__ method and be used as a collection.[2]

Type classes in languages like Haskell, or module signatures in ML and OCaml, are used for many of the things that protocols are used for.[clarification needed]

See also

Notes

  1. ^ Usage of these terms varies by programming language. Java and languages derived from it tend to use "interface", while "protocol" is generally more popular elsewhere.

References

  1. ^ a b "Interfaces - define behavior for multiple types". learn.microsoft.com. Retrieved 16 November 2022.
  2. ^ "Glossary — Python 3.11.0 documentation". docs.python.org. Retrieved 16 November 2022.