Interface (object-oriented programming) explained

In object-oriented programming, an interface or protocol type is a data type that acts as an abstraction of a class. It describes 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 a protocol is said to adopt the protocol,[2] or to implement the 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, Python 3.8). 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.[3]

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.

In Rust, interfaces are called traits.[4]

See also

Notes and References

  1. Web site: Interfaces - define behavior for multiple types . learn.microsoft.com . 16 November 2022 . en-us.
  2. Book: Miller . BJ . Sams Teach Yourself Swift in 24 hours . 2015 . Indianapolis, Indiana . 978-0-672-33724-6 . 263 . Any type can adopt a protocol to help give it extra functionality to accomplish a particular set of tasks..
  3. Web site: Glossary — Python 3.11.0 documentation . docs.python.org . 16 November 2022.
  4. Web site: Traits - The Rust Reference. January 2024.