Interface (Java): Difference between revisions

Content deleted Content added
No edit summary
AnomieBOT (talk | contribs)
m Dating maintenance tags: {{When}}
 
(95 intermediate revisions by 69 users not shown)
Line 1:
{{Short description|Concept in the Java computer programming language}}
An '''interface''' in the [[Java (programming language)|Java programming language]] is an [[abstract type]] that is used to specifydeclare ana behavior that [[interfaceclass (computer science)|interfaceclasses]] (inmust theimplement. genericThey senseare ofsimilar the term) thatto [[classProtocol (computerobject-oriented scienceprogramming)|classesprotocol]] must implements. Interfaces are declared using the '''<code>interface</code>''' [[Java keywords|keyword]], and may only contain [[method signature]] and constant declarations (variable declarations that are declared to be both <code>[[Static_variable#Static_Variables_as_Class_Variables|static]]</code> and <code>[[Final (Java)|final]]</code>). All methods of an Interface do not contain implementation (method bodies) as of all versions below JAVAJava 8. Starting with <strong>Java 8<strong>, <code>default</code>{{sfn|Bloch|2018}}{{rp|99}} and <code>static</code>{{sfn|Bloch|2018}}{{rp|7}} methods may have implementation in the <code>interface</code> definition.<ref>{{cite web|url=http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html|title=Default Methods|access-date=2014-06-30|archive-url=https://web.archive.org/web/20170523042436/http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html|archive-date=2017-05-23|url-status=dead}}</ref> Then, in Java 9, <code>private</code> and <code>private static</code> methods were added. At present,{{when|date=March 2025}} a Java interface can have up to six different types.{{Clarify|date=March 2025}}
 
Interfaces cannot be [[Instance (computer science)|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]]. Object references in Java may be specified to be of an interface type; in whicheach case, they must either be [[null pointer|null]], or be bound to an object that implements the interface.
 
One benefit of using interfaces is that they simulate [[multiple inheritance]]. All classes in Java must have exactly one [[base class]], the only exception being {{Javadoc:SE|package=java.lang|java/lang|Object}} (the [[top type|root class]] of the Java [[type system]]); [[multiple inheritance]] of classes is not allowed. However, an interface may inherit multiple interfaces and a class may implement multiple interfaces.
 
A Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
 
== 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]] and a [[parrot]] can both [[whistle]]; however, it would not make sense to represent <code>Human</code>s and <code>Parrot</code>s as subclasses of a <code>Whistler</code> class. Rather they would most likely be subclasses of an <code>Animal</code> class (likely with intermediate classes), but both would implement the <code>Whistler</code> interface.
 
Another use of interfaces is being able to use an [[Object (computer science)|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 <code>whistler.whistle()</code> will call the implemented method <code>whistle</code> of object <code>whistler</code> no matter what class it has, provided it implements <code>Whistler</code>. In a more practical example, a [[sorting algorithm]] may expect an object of type {{Javadoc:SE|java/lang|Comparable}}. Thus, itwithout knows thatknowing the object'sspecific type can somehow be sorted, but it isknows irrelevantthat whatobjects theof that type ofcan thesomehow objectbe issorted.
 
For example:-
<sourcesyntaxhighlight lang="Java">
interface Bounceable {
double pi = 3.1415;
void setBounce(); // Note the semicolon
// Interface methods are public, abstract and never final.
// Think of them as prototypes only; no implementations are allowed.
}
</syntaxhighlight>
 
An interface:
<source lang="Java">
* declares only method headers and public constants.
interface Bounceable {
* cannot be instantiated.
void setBounce(); // Note the semicolon
* can be implemented by a class.{{sfn|Bloch|2018}}{{rp|75}}
// Interface methods are public, abstract and never final.
* cannot extend a class.
// Think of them as prototypes only; no implementations are allowed.
* can extend several other interfaces.{{sfn|Bloch|2018}}{{rp|87}}
}
</source>
 
==Usage==
Line 30 ⟶ 36:
''constant declarations''
''abstract method declarations''
'' static method declarations''
}
 
Example: public interface Interface1 extends Interface2;
The body of the interface contains abstract [[Method (computer science)|methods]], but since all methods in an interface are, by definition, abstract, the <code>abstract</code> keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitly <code>public</code>.
 
The body of the interface contains abstract [[Method (computer scienceprogramming)#Abstract methods|abstract methods]], but since all methods in an interface are, by definition, abstract, the <code>abstract</code> keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitly <code>public</code>.
 
Thus, a simple interface may be
<sourcesyntaxhighlight lang="java">
public interface Predator {
boolean chasePrey(Prey p);
void eatPrey(Prey p);
}
</syntaxhighlight>
</source>
 
The member type declarations in an interface are implicitly static, final and public, but otherwise they can be any type of class or interface.<ref>{{cite web|url=http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.5|title=The Java Language Specification}}</ref>'''
 
===Implementing interfaces in a class===
The syntax for implementing an interface uses this formula:
 
... implements ''InterfaceName''[, ''another interface'', ''another'', ...] ...
 
[[Class (software)|Classes]] may implement an interface. For example, :
<sourcesyntaxhighlight lang="java">
public class Lion implements Predator {
 
@Override
public boolean chasePrey(Prey p) {
// programmingProgramming to chase prey p (specifically for a lion)
}
 
@Override
public void eatPrey(Prey p) {
// programmingProgramming to eat prey p (specifically for a lion)
}
}
</syntaxhighlight>
</source>
If a class implements an interface and does not implement all its methods, it must be marked as <code>abstract</code>. If a class is abstract, one of its [[Subclass (computer science)|subclasses]] is expected to implement its unimplemented methods., Althoughthough if any of the abstract class' subclasses doesdo not implement all interface methods, the subclass itself must be marked again as <code>abstract</code>.
 
Classes can implement multiple interfaces:
<sourcesyntaxhighlight lang="Java">
public class Frog implements Predator, Prey { ... }
</syntaxhighlight>
</source>
 
Interfaces can share common class methods:
Interfaces are commonly used in the Java language for [[Callback (computer science)|callbacks]].<ref>{{cite web|url=http://www.javaworld.com/javaworld/javatips/jw-javatip10.html|title=Java World}}</ref> Java does not allow the passing of methods (procedures) as arguments. Therefore, the practice is to define an interface and use it as the argument and use the method signature knowing that the signature will be later implemented.
<syntaxhighlight lang="Java">
class Animal implements LikesFood, LikesWater {
boolean likes() { return true; }
}
</syntaxhighlight>
 
However a given class cannot implement the same or a similar interface multiple times:
<syntaxhighlight lang="Java">
class Animal implements Shares<Boolean>, Shares<Integer> ...
// Error: repeated interface
</syntaxhighlight>
 
Interfaces are commonly used in the Java language for [[Callback (computer science)|callbacks]],<ref>{{cite web |last1=Mitchell |first1=John D. |date=1996-06-01 |df=mdy |url=https://www.infoworld.com/article/2077462/java-tip-10--implement-callback-routines-in-java.html |title=Java Tip 10: Implement callback routines in Java |work=[[JavaWorld]] |access-date=2020-07-14}}</ref> 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,
<sourcesyntaxhighlight lang="java">
public interface VenomousPredator extends Predator, Venomous {
//interface Interface body
}
</syntaxhighlight>
</source>
is legal and defines a subinterface. Note how itIt allows multiple inheritance, unlike classes. Note also that <code>Predator</code> and <code>Venomous</code> may possibly define or inherit methods with the same signature, say <code>kill(Prey p)</code>. When a class implements <code>VenomousPredator</code> it will implement both methods simultaneously.
 
==Examples==
Some common [[Java (Sun)|Java]] interfaces are:
* {{Javadoc:SE|java/lang|Comparable}} has the method {{Javadoc:SE|name=compareTo|java/lang|Comparable|compareTo(T)}}, which is used to describe two objects as equal, or to indicate one is greater than the other. [[Generic programming|Generics]] allow implementing classes to specify which class instances can be compared to them.
* {{Javadoc:SE|java/io|Serializable}} is a [[marker interface]] with no methods or fields - it has an empty body. It is used to indicate that a class can be [[Serialization|serialized]]. Its [[Javadoc]] describes how it should function, although nothing is programmatically enforced.
 
==See also==
* [[Interface (object-oriented programming)]]
* [[Mixin]]
* [[Trait (computer programming)|Traits]]
 
==ReferencesCitations==
{{reflist}}
 
==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==
* [http://java.sun.com/docs/books/tutorial/java/concepts/interface.html What Is an Interface?]
 
[[Category:Java (programming language)]]
[[Category:Interfaces]]
[[Category:Articles with example Java code]]
 
[[de:Schnittstelle (Objektorientierung)]]
[[pl:Interfejs (Java)]]
[[ru:Интерфейс (объектно-ориентированное программирование)]]