Aninterface in theJava programming language is anabstract type that is used to declare a behavior thatclasses must implement. They are similar toprotocols. Interfaces are declared using theinterfacekeyword, and may only containmethod signature and constant declarations (variable declarations that are declared to be bothstatic andfinal). All methods of an Interface do not contain implementation (method bodies) as of all versions below Java 8. Starting with Java 8,default[1]: 99 andstatic[1]: 7 methods may have implementation in theinterface definition.[2] Then, in Java 9,private andprivate static methods were added. At present,[when?] a Java interface can have up to six different types.[clarification needed] Such interfaces exist inC#.
Interfaces cannot beinstantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be anabstract class. Object references in Java may be specified to be of an interface type; in each case, they must either benull, or be bound to an object that implements the interface.
One benefit of using interfaces is that they simulatemultiple inheritance. All classes in Java must have exactly onebase class, the only exception beingjava.lang.Object (theroot class of the Javatype system);multiple inheritance of classes is not allowed. However, an interface may inherit multiple interfaces and a class may implement multiple interfaces.
Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. For instance, ahuman and aparrot can bothwhistle; however, it would not make sense to representHumans andParrots as subclasses of aWhistler class. Rather they most likely be subclasses of anAnimal class (likely with intermediate classes), but both would implement theWhistler interface.
Another use of interfaces is being able to use anobject 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 callwhistler.whistle() will call the implemented methodwhistle of objectwhistler no matter what class it has, provided it implementsWhistler. In a more practical example, asorting algorithm may expect an object of typeComparable. Thus, without knowing the specific type, it knows that objects of that type can somehow be sorted.
For example:
interfaceBounceable{doublepi=3.1415;// Note the semicolon// Interface methods are public, abstract and never final.// They are usually meant as prototypes, but default implementations are allowedvoidsetBounce();}
An interface:
Interfaces are defined with the following syntax (compare toJava's class definition):
[visibility] interfaceInterfaceName [extendsother interfaces] {constant declarationsabstract method declarations static method declarations}Example:
publicinterfaceInterface1extendsInterface2,Interface3,Interface4;
The body of the interface containsabstract methods, but since all methods in an interface are, by definition, abstract, theabstract keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitlypublic.
Thus, a simple interface may be
publicinterfacePredator{booleanchasePrey(Preyp);voideatPrey(Preyp);}
The member type declarations in an interface are implicitly static, final and public, but otherwise they can be any type of class or interface.[3]
The syntax for implementing an interface uses this formula:
... implementsInterfaceName[,another interface,another, ...] ...
Classes may implement an interface. For example:
publicclassLionextendsAnimalimplementsPredator{@OverridepublicbooleanchasePrey(Preyp){// Programming to chase prey p (specifically for a lion)}@OverridepublicvoideatPrey(Preyp){// Programming to eat prey p (specifically for a lion)}}
If a class implements an interface and does not implement all its methods, it must be marked asabstract. If a class is abstract, one of itssubclasses 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 asabstract.
Classes can implement multiple interfaces:
publicclassFrogextendsAnimalimplementsPredator,Prey{// ...}
Interfaces can share common class methods:
abstractclassAnimalimplementsLikesFood,LikesWater{booleanlikes(){returntrue;}}
However a given class cannot implement the same or a similar interface multiple times:
// Error: repeated interfaceabstractclassAnimalimplementsShares<Boolean>,Shares<Integer>...{// ...}
Interfaces are commonly used in the Java language forcallbacks,[4] 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.
Interfaces can extend several other interfaces, using the same formula as described below. For example,
publicinterfaceVenomousPredatorextendsPredator,Venomous{// Interface body}
is legal and defines a subinterface. It allows multiple inheritance, unlike classes.Predator andVenomous may possibly define or inherit methods with the same signature, saykill(Prey p). When a class implementsVenomousPredator it will implement both methods simultaneously.
Some commonJava interfaces are:
Comparable has the methodcompareTo, 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.Serializable is amarker interface with no methods or fields - it has an empty body. It is used to indicate that a class can beserialized. ItsJavadoc describes how it should function, although nothing is programmatically enforced