An interface in the
Java programming language
Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let programmers ''write once, run anywh ...
is an
abstract type
In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Every instance of an abstrac ...
that is used to describe a behavior that
classes must implement. They are similar to
protocol
Protocol may refer to:
Sociology and politics
* Protocol (politics), a formal agreement between nation states
* Protocol (diplomacy), the etiquette of diplomacy and affairs of state
* Etiquette, a code of personal behavior
Science and technolog ...
s. Interfaces are declared using the
interface
keyword
Keyword may refer to:
Computing
* Keyword (Internet search), a word or phrase typically used by bloggers or online content creator to rank a web page on a particular topic
* Index term, a term used as a keyword to documents in an information syst ...
, and may only contain
method signature and constant declarations (variable declarations that are declared to be both
static
Static may refer to:
Places
*Static Nunatak, a nunatak in Antarctica
United States
* Static, Kentucky and Tennessee
*Static Peak, a mountain in Wyoming
**Static Peak Divide, a mountain pass near the peak
Science and technology Physics
*Static el ...
and
final
Final, Finals or The Final may refer to:
*Final (competition), the last or championship round of a sporting competition, match, game, or other contest which decides a winner for an event
** Another term for playoffs, describing a sequence of cont ...
). 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 programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Every instance of an abstra ...
. 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 Computing
* Null (SQL) (or NULL), a special marker and keyword in SQL indicating that something has no value
* Null character, the zero-valued ASCII character, also designated by , often use ...
, 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 or ...
. All classes in Java must have exactly one
base class
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
, 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 to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
);
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 or ...
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'') are the most abundant and widespread species of primate, characterized by bipedalism and exceptional cognitive skills due to a large and complex brain. This has enabled the development of advanced tools, culture, ...
and a
parrot
Parrots, also known as psittacines (), are birds of the roughly 398 species in 92 genera comprising the order Psittaciformes (), found mostly in tropical and subtropical regions. The order is subdivided into three superfamilies: the Psittacoide ...
can both
whistle
A whistle is an instrument which produces sound from a stream of gas, most commonly air. It may be mouth-operated, or powered by air pressure, steam, or other means. Whistles vary in size from a small slide whistle or nose flute type to a lar ...
; however, it would not make sense to represent
Human
s and
Parrot
s 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
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
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 (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
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
The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support ...
with no methods or fields - it has an empty body. It is used to indicate that a class can be
serialized. Its
Javadoc
Javadoc (originally cased JavaDoc) is a documentation generator created by Sun Microsystems for the Java language (now owned by Oracle Corporation) for generating API documentation in HTML format from Java source code. The HTML format is used for ...
describes how it should function, although nothing is programmatically enforced
See also
*
Mixin
In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depen ...
*
Trait (computer programming)
In computer programming, a trait is a concept used in object-oriented programming which represents a set of methods that can be used to extend the functionality of a class.
Rationale
In object-oriented programming, behavior is sometimes share ...
References
{{reflist
External links
What Is an Interface?
Java (programming language)
Interfaces
Articles with example Java code