Inobject-oriented programming, aninterface orprotocol type[a] is adata type that acts as anabstraction of aclass. It describes a set ofmethod signatures, the implementations of which may be provided by multipleclasses that are otherwise not necessarily related to each other.[1] A class which provides the methods listed in an interface is said toimplement the interface,[1] or toadopt the protocol.[2]
If objects are fullyencapsulated then the interface 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 languages provide explicit language support for interfaces:Ada,C#,D,Dart,Delphi,Go,Java,Logtalk,Object Pascal,Objective-C,OCaml,PHP,Racket,Seed7,Swift,Python 3.8. In languages supportingmultiple inheritance, such asC++, interfaces are implemented asabstract classes.
In languages without explicit support, interfaces 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 classes in languages likeHaskell, or module signatures inML andOCaml, are used for many of the things that interfaces are used for.[clarification needed]
InRust, interfaces are calledtraits.[4]
Any type canadopt a protocol to help give it extra functionality to accomplish a particular set of tasks.
{{cite book}}
: CS1 maint: location missing publisher (link)