Inobject-oriented programming,aninterfaceorprotocoltype[a]is adata typethat acts as anabstractionof aclass.It describes a set ofmethod signatures,the implementations of which may be provided by multipleclassesthat are otherwise not necessarily related to each other.[1]A class which provides the methods listed in a protocol is said toadoptthe protocol,[2]or toimplementthe interface.[1]
If objects are fullyencapsulatedthen the protocol is the only way in which they may be accessed by other objects. For example, inJava,theComparable
interface specifies a methodcompareTo()
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 ofcompareTo()
).
Someprogramming languagesprovide explicit language support for protocols (Ada,C#,D,Dart,Delphi,Go,Java,Logtalk,Object Pascal,Objective-C,OCaml,PHP,Racket,Seed7,Swift,Python3.8). In languages supportingmultiple inheritance,such asC++,interfaces are implemented asabstract classes.
In languages without explicit support, protocols are often still present as conventions. This is known asduck typing.For example, inPython,any class can implement an__iter__
method and be used as acollection.[3]
Type classesin languages likeHaskell,or module signatures inMLandOCaml,are used for many of the things that protocols are used for.[clarification needed]
See also
editNotes
edit- ^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
edit- ^ab"Interfaces - define behavior for multiple types".learn.microsoft.com.Retrieved16 November2022.
- ^Miller, BJ (2015).Sams Teach Yourself Swift in 24 hours.Indianapolis, Indiana. p. 263.ISBN978-0-672-33724-6.
Any type canadopta protocol to help give it extra functionality to accomplish a particular set of tasks.
{{cite book}}
:CS1 maint: location missing publisher (link) - ^"Glossary — Python 3.11.0 documentation".docs.python.org.Retrieved16 November2022.
- ^"Traits - The Rust Reference".January 2024.