HOME

TheInfoList



OR:

An interface in the
Java programming language Java is a high-level, general-purpose, memory-safe, object-oriented programming language. It is intended to let programmers ''write once, run anywhere'' ( WORA), meaning that compiled Java code can run on all platforms that support Jav ...
is an
abstract type In programming languages, an abstract type (also known as existential types) is a type in a nominative type system that cannot be instantiated directly; by contrast, a concrete type be instantiated directly. Instantiation of an abstract ty ...
that is used to declare a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and
final Final, Finals or The Final may refer to: *Final examination or finals, a test given at the end of a course of study or training *Final (competition), the last or championship round of a sporting competition, match, game, or other contest which d ...
). All methods of an Interface do not contain implementation (method bodies) as of all versions below Java 8. Starting with Java 8, default and static methods may have implementation in the interface definition. Then, in Java 9, private and private static methods were added. At present, a Java interface can have up to six different types. Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an
abstract class In object-oriented programming, a class defines the shared aspects of objects created from the class. The capabilities of a class differ between programming languages, but generally the shared aspects consist of state ( variables) and behavior ( ...
. Object references in Java may be specified to be of an interface type; in each case, they must either be
null Null may refer to: Science, technology, and mathematics Astronomy *Nuller, an optical tool using interferometry to block certain sources of light Computing *Null (SQL) (or NULL), a special marker and keyword in SQL indicating that a data value do ...
, or be bound to an object that implements the interface. One benefit of using interfaces is that they simulate
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object ...
. All classes in Java must have exactly one base class, the only exception being (the root class of the Java
type system In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
);
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object ...
of classes is not allowed. However, an interface may inherit multiple interfaces and a class may implement multiple interfaces.


Overview

Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. For instance, a
human Humans (''Homo sapiens'') or modern humans are the most common and widespread species of primate, and the last surviving species of the genus ''Homo''. They are Hominidae, great apes characterized by their Prehistory of nakedness and clothing ...
and a
parrot Parrots (Psittaciformes), also known as psittacines (), are birds with a strong curved beak, upright stance, and clawed feet. They are classified in four families that contain roughly 410 species in 101 genus (biology), genera, found mostly in ...
can both whistle; however, it would not make sense to represent Humans and Parrots as subclasses of a Whistler class. Rather they most likely be subclasses of an Animal class (likely with intermediate classes), but both would implement the Whistler interface. Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface. For instance, if one were annoyed by a whistling noise, one may not know whether it is a human or a parrot, because all that could be determined is that a whistler is whistling. The call whistler.whistle() will call the implemented method whistle of object whistler no matter what class it has, provided it implements Whistler. In a more practical example, a
sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending ...
may expect an object of type . Thus, without knowing the specific type, it knows that objects of that type can somehow be sorted. For example: interface Bounceable An interface: * declares only method headers and public constants. * cannot be instantiated. * can be implemented by a class. * cannot extend a class. * can extend several other interfaces.


Usage


Defining an interface

Interfaces are defined with the following syntax (compare to Java's class definition): 'visibility''interface ''InterfaceName'' xtends ''other interfaces'' Example: public interface Interface1 extends Interface2; The body of the interface contains abstract methods, but since all methods in an interface are, by definition, abstract, the abstract keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitly public. Thus, a simple interface may be public interface Predator The member type declarations in an interface are implicitly static, final and public, but otherwise they can be any type of class or interface.


Implementing interfaces in a class

The syntax for implementing an interface uses this formula: ... implements ''InterfaceName'' ''another interface'', ''another'', ...... Classes may implement an interface. For example: public class Lion implements Predator If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods, though if any of the abstract class' subclasses do not implement all interface methods, the subclass itself must be marked again as abstract. Classes can implement multiple interfaces: public class Frog implements Predator, Prey Interfaces can share common class methods: class Animal implements LikesFood, LikesWater However a given class cannot implement the same or a similar interface multiple times: class Animal implements Shares, Shares ... // Error: repeated interface Interfaces are commonly used in the Java language for callbacks, as Java does not allow multiple inheritance of classes, nor does it allow the passing of methods (procedures) as arguments. Therefore, in order to pass a method as a parameter to a target method, current practice is to define and pass a reference to an interface as a means of supplying the signature and address of the parameter method to the target method rather than defining multiple variants of the target method to accommodate each possible calling class.


Subinterfaces

Interfaces can extend several other interfaces, using the same formula as described below. For example, public interface VenomousPredator extends Predator, Venomous is legal and defines a subinterface. It allows multiple inheritance, unlike classes. Predator and Venomous may possibly define or inherit methods with the same signature, say kill(Prey p). When a class implements VenomousPredator it will implement both methods simultaneously.


Examples

Some common
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
interfaces are: * has the method , which is used to describe two objects as equal, or to indicate one is greater than the other. Generics allow implementing classes to specify which class instances can be compared to them. * is a marker interface with no methods or fields - it has an empty body. It is used to indicate that a class can be serialized. Its
Javadoc Javadoc (also capitalized as JavaDoc or javadoc) is an API documentation generator for the Java programming language. Based on information in Java source code, Javadoc generates documentation formatted as HTML and other formats via extensions. ...
describes how it should function, although nothing is programmatically enforced


See also

*
Interface (object-oriented programming) In object-oriented programming, an interface or protocol type is a data type that acts as an abstraction of a Class (computer science), class. It describes a set of method signatures, the implementations of which may be provided by multiple class ( ...
* Mixin * Trait (computer programming)


Citations


References

*{{cite book , title= "Effective Java: Programming Language Guide" , last=Bloch, first=Joshua, publisher=Addison-Wesley , edition=third , isbn=978-0134685991, year=2018


External links


What Is an Interface?
Java (programming language) Interfaces Articles with example Java code