Interface (object-oriented programming): Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>Villaida
removed stub template
 
Line 1: Line 1:
{{Short description|Abstraction of a class}}
{{Short description|Abstraction of a class}}
In [[object-oriented programming]], an '''interface''' or '''protocol''' type{{efn|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.}} is a [[data type]] that acts as an [[abstraction]] of a [[Class (computer science)|class]]. It describes a set of [[method signature]]s, the implementations of which may be provided by multiple [[class (computer programming)|class]]es that are otherwise not necessarily related to each other.<ref name="csharp-learn">{{cite web |title=Interfaces - define behavior for multiple types |url=https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/interfaces |website=learn.microsoft.com |access-date=16 November 2022 |language=en-us}}</ref> A class which provides the methods listed in an interface is said to ''implement'' the interface,<ref name="csharp-learn" /> or to ''adopt'' the protocol.<ref name="swift-24h">{{cite book |last1=Miller |first1=BJ |title=Sams Teach Yourself Swift in 24 hours |date=2015 |location=Indianapolis, Indiana |isbn=978-0-672-33724-6 |page=263 |quote=Any type can '''adopt''' a protocol to help give it extra functionality to accomplish a particular set of tasks.}}</ref>
In [[object-oriented programming]], an '''interface''' or '''protocol''' type{{efn|Use of these terms varies by programming language. Java and languages derived from it tend to use ''interface'', while ''protocol'' is generally more popular elsewhere.}} is a [[data type]] that acts as an [[abstraction]] of a [[Class (computer science)|class]]. It describes a set of [[method signature]]s, the implementations of which may be provided by multiple [[class (computer programming)|class]]es that are otherwise not necessarily related to each other.<ref name="csharp-learn">{{cite web |title=Interfaces - define behavior for multiple types |url=https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/interfaces |website=learn.microsoft.com |access-date=16 November 2022 |language=en-us}}</ref> A class which provides the methods listed in an interface is said to ''implement'' the interface,<ref name="csharp-learn"/> or to ''adopt'' the protocol.<ref name="swift-24h">{{cite book |last1=Miller |first1=BJ |title=Sams Teach Yourself Swift in 24 hours |date=2015 |location=Indianapolis, Indiana |isbn=978-0-672-33724-6 |page=263 |quote=Any type can '''adopt''' a protocol to help give it extra functionality to accomplish a particular set of tasks.}}</ref>


<!-- rewrite todo: probably move this to an examples section later -->== Examples ==
Interfaces are useful for [[Encapsulation (computer programming)|encapsulation]] and reducing [[Coupling (computer programming)|coupling]]. For example, in [[Java (programming language)|Java]], the <code>Comparable</code> interface specifies the method <code>compareTo</code>. Thus, a sorting method only needs to take objects of types which implement <code>Comparable</code> to sort them, without knowing about the inner nature of the class (except that two of these objects can be compared via <code>compareTo()</code>).
If objects are fully [[encapsulation (object-oriented programming)|encapsulated]] then the interface is the only way in which they may be accessed by other objects. For example, in [[Java (programming language)|Java]], the <code>Comparable</code> interface specifies a method <code>compareTo()</code> 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 <code>compareTo()</code>).


Some [[programming language]]s provide explicit language support for interfaces: [[Ada (programming language)|Ada]], [[C Sharp (programming language)|C#]], [[D (programming language)|D]], [[Dart (programming language)|Dart]], [[Delphi (programming language)|Delphi]], [[Go (programming language)|Go]], [[Java (programming language)|Java]], [[Logtalk]], [[Object Pascal]], [[Objective-C]], [[OCaml]], [[PHP]], [[Racket (programming language)|Racket]], [[Seed7]], [[Swift (programming language)|Swift]], [[Python (programming language)|Python]] 3.8. In languages supporting [[multiple inheritance]], such as [[C++]], interfaces are implemented as [[abstract class]]es.
== Examples ==
Some [[programming language]]s provide explicit language support for interfaces: [[Ada (programming language)|Ada]], [[C Sharp (programming language)|C#]], [[D (programming language)|D]], [[Dart (programming language)|Dart]], [[Delphi (software)|Delphi]], [[Go (programming language)|Go]], [[Java (programming language)|Java]], [[Logtalk]], [[Object Pascal]], [[Objective-C]], [[OCaml]], [[PHP]], [[Racket (programming language)|Racket]], [[Swift (programming language)|Swift]], [[Python (programming language)|Python]] 3.8. In languages supporting [[multiple inheritance]], such as [[C++]], interfaces are [[abstract class]]es.


In languages without explicit support, interfaces are often still present as conventions; this is known as [[duck typing]]. For example, in [[Python (programming language)|Python]], any class can implement an <code>__iter__</code> method and be used as a [[Collection (abstract data type)|collection]].<ref name="python-iter">{{cite web |title=Glossary — Python 3.11.0 documentation |url=https://docs.python.org/3/glossary.html#term-iterable |website=docs.python.org |access-date=16 November 2022}}</ref>
In Java, an implementation of interfaces may look like:


[[Type class]]es in languages like [[Haskell (programming language)|Haskell]], or module signatures in [[ML (programming language)|ML]] and [[OCaml]], are used for many of the things that interfaces are used for.{{clarify|date=November 2022}}
<syntaxhighlight lang="java">
class Animal { ... }
class Theropod extends Animal { ... }


In [[Rust (programming language)|Rust]], interfaces are called ''trait''s.<ref>{{cite web|title=Traits - The Rust Reference|date=January 2024|url=https://doc.rust-lang.org/reference/items/traits.html}}</ref>
interface Flyable {
    void fly();
}


==See also==
interface Vocal {
    void vocalize();
}
 
public class Bird extends Theropod implements Flyable, Vocal {
    // ...
    public void fly() { ... }
    public void vocalize() { ... }
}
</syntaxhighlight>
 
In languages without explicit support, interfaces are often still present as conventions; this is known as [[duck typing]]. For example, in [[Python (programming language)|Python]], any class can implement an <code>__iter__</code> method and be used as an [[Iterator|iterable]].<ref name="python-iter">{{cite web |title=Glossary — Python 3.11.0 documentation |url=https://docs.python.org/3/glossary.html#term-iterable |website=docs.python.org |access-date=16 November 2022}}</ref> Classes may also explicitly subclass an [[Abstract base class|ABC]], such as {{Code|collections.abc.Iterable}}.
 
[[Type class]]es in languages like [[Haskell]], or module signatures in [[ML (programming language)|ML]] and [[OCaml]], are used for many of the same things as are interfaces.{{clarify|date=November 2022}}
 
In [[Rust (programming language)|Rust]], interfaces are called ''traits''.<ref>{{cite web|title=Traits - The Rust Reference|date=January 2024|url=https://doc.rust-lang.org/reference/items/traits.html}}</ref> In Rust, a <code>struct</code> does not contain methods, but may add methods through separate {{Code|impl}} blocks:
 
<syntaxhighlight lang="rust">
trait Pet {
    fn speak(&self);
}
 
struct Dog {
    // Structs only contain their fields
    name: String
}
 
impl Dog {
    // Not from a trait
    fn new(name: String) -> Self {
        Dog { name }
    }
}
 
impl Pet for Dog {
    // From a trait
    fn speak(&self) {
        println!("{} says 'Woof!'", self.name);
    }
}
 
fn main() {
    let dog = Dog::new(String::from("Arlo"));
    dog.speak();
}
</syntaxhighlight>
 
== See also ==
* [[Interface (computing)]]
* [[Objective-C#Protocols|Protocols in Objective-C]]
* [[Interface (Java)]]
* [[Concept (generic programming)]]
* [[Concept (generic programming)]]
* [[Delegation (programming)]]
* [[Delegation (programming)]]
* [[Objective-C#Protocols|Protocols in Objective-C]]
* [[Class (computer science)]]
* [[Class (computer science)]]
* [[Encapsulation (computer science)]]
* [[Public interface]]
* [[Interface (Java)]]
* [[Application programming interface]]
* [[Application programming interface]]
* [[Interface (computing)]]
* [[List of basic computer science topics]]


==Notes==
== Notes ==
{{notelist}}
{{Notelist}}


==References==
== References ==
{{Reflist}}


{{reflist}}
{{Data types}}
{{Data types}}


{{DEFAULTSORT:Protocol (Object-priented programming)}}
{{DEFAULTSORT:Protocol (Object-oriented programming)}}
 
[[Category:Object-oriented programming]]
[[Category:Object-oriented programming]]
[[Category:Data types]]
[[Category:Data types]]
[[Category:Programming language comparisons]]
<!-- Hidden categories below -->
[[Category:Articles with example Java code]]
[[Category:Articles with example Rust code]]

Latest revision as of 20:06, 15 October 2025

Template:Short description In object-oriented programming, an interface or protocol typeTemplate:Efn 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 Comparable interface specifies the method compareTo. Thus, a sorting method only needs to take objects of types which implement Comparable to sort them, without knowing about the inner nature of the class (except that two of these objects can be compared via compareTo()).

Examples

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:

class Animal { ... }
class Theropod extends Animal { ... }

interface Flyable {
    void fly();
}

interface Vocal {
    void vocalize();
}

public class Bird extends Theropod implements Flyable, Vocal {
    // ...
    public void fly() { ... }
    public void vocalize() { ... }
}

In languages without explicit support, interfaces 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 an iterable.[3] Classes may also explicitly subclass an ABC, such as collections.abc.Iterable.

Type classes in languages like Haskell, or module signatures in ML and OCaml, are used for many of the same things as are interfaces.Template:Clarify

In Rust, interfaces are called traits.[4] In Rust, a struct does not contain methods, but may add methods through separate impl blocks:

trait Pet {
    fn speak(&self);
}

struct Dog {
    // Structs only contain their fields
    name: String
}

impl Dog {
    // Not from a trait
    fn new(name: String) -> Self {
        Dog { name }
    }
}

impl Pet for Dog {
    // From a trait
    fn speak(&self) {
        println!("{} says 'Woof!'", self.name);
    }
}

fn main() {
    let dog = Dog::new(String::from("Arlo"));
    dog.speak();
}

See also

Notes

Template:Notelist

References

Template:Reflist

Template:Data types

  1. a b Script error: No such module "citation/CS1".
  2. Script error: No such module "citation/CS1".
  3. Script error: No such module "citation/CS1".
  4. Script error: No such module "citation/CS1".