| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Interface_(computer_programming) |
In object-oriented programming, an interface or protocol type 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. A class which provides the methods listed in an interface is said to implement the interface, or to adopt the protocol.
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()).
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.traitPet{ fnspeak(&self); } structDog{ // Structs only contain their fields name:String } implDog{ // Not from a trait fnnew(name:String)->Self{ Dog{name} } } implPetforDog{ // From a trait fnspeak(&self){ println!("{} says 'Woof!'",self.name); } } fnmain(){ letdog=Dog::new(String::from("Arlo")); dog.speak(); }
In C++, there are multiple ways to resemble interfaces. One such way is the Java-style interface, which is done using abstract classes. The other, which resembles Go interfaces, is using concepts. Unlike inheritance, with concepts any type may satisfy a concept (not just classes) so long as it satisfies all of its requirements.