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 an interface is said to implement the interface,[1] or to adopt the protocol.[2]
Interfaces are useful for encapsulation and reducing coupling. For example, in Java, the java.lang.Comparable<T> interface specifies the method compareTo(). Thus, a sorting method only needs to take objects of types which implement java.lang.Comparable<T> to sort them, without knowing about the inner nature of the class (except that two of these objects can be compared via compareTo()).
Some programming languages provide explicit language support for interfaces: Ada, C#, D, Dart, Delphi, Go, Java, Logtalk, Object Pascal, Objective-C, OCaml, PHP, Racket, Swift, Python 3.8. In languages supporting multiple inheritance, such as C++, interfaces are abstract classes.
In Java, an implementation of interfaces may look like:
classAnimal{...}classTheropodextendsAnimal{...}interfaceFlyable{voidfly();}interfaceVocal{voidvocalize();}publicclassBirdextendsTheropodimplementsFlyable,Vocal{// ...publicvoidfly(){...}publicvoidvocalize(){...}}明示的なサポートがない言語では、インターフェースは慣習として存在することが多く、これはダックタイピングとして知られています。たとえば、Pythonでは、任意のクラスがメソッドを実装してイテラブル__iter__として使用できます。[ 3 ]クラスは、ABCを明示的にサブクラス化することもできます。collections.abc.Iterable
Haskellのような言語における型クラスや、MLやOCamlにおけるモジュールシグネチャは、インターフェースとほぼ同じ目的で使用されます。
Rustでは、インターフェースはトレイトと呼ばれます。[ 4 ] Rust では、インターフェースにはstructメソッドは含まれませんが、別のimplブロックを介してメソッドを追加できます。
trait Pet { fn speak ( & self ); }struct Dog { // 構造体にはフィールドのみが含まれますname : String }impl Dog { // トレイト由来ではないfn new ( name : String ) -> Self { Dog { name } } }impl Pet for Dog { // 特性からfn speak ( & self ) { println! ( "{} says 'Woof!'" , self . name ); } }fn main ( ) { let dog = Dog :: new ( String :: from ( "Arlo" )); dog.speak ( ); }C++では、インターフェースに似たものを実現する方法は複数あります。その一つは、抽象クラスを用いるJavaスタイルのインターフェースです。もう一つは、Goのインターフェースに似た概念を用いる方法です。継承とは異なり、概念では、すべての要件を満たしていれば、クラスだけでなく、あらゆる型が概念を満たすことができます。
どのような種類のシステムでも、
特定のタスクを実行するための追加機能を持たせるために、プロトコル
を採用することができます。
{{cite book}}: CS1メンテナンス: 場所の発行元が見つかりません (リンク)