In object-oriented programming, an interface or protocol type[a] 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()).
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]
^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.
^Miller, BJ (2015). Sams Teach Yourself Swift in 24 hours. Indianapolis, Indiana. p. 263. ISBN978-0-672-33724-6. Any type can adopt a protocol to help give it extra functionality to accomplish a particular set of tasks.{{cite book}}: CS1 maint: location missing publisher (link)