| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Interface_(Java) |
| Contents |
|---|
| Usage |
| Defining an interface |
| Subinterfaces |
An interface in the Java programming language is an abstract type 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). 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,java.lang.Object (the 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.
interface Bounceable{ doublepi=3.1415; // Note the semicolon // Interface methods are public, abstract and never final. // They are usually meant as prototypes, but default implementations are allowed voidsetBounce(); }An interface:
Interfaces are defined with the following syntax (compare to Java's class definition):
[visibility] interface InterfaceName [extends other interfaces] { constant declarations abstract method declarations static method declarations }Example:
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:
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.
Interfaces can extend several other interfaces, using the same formula as described below. For example,
| View original on Wikipedia | Back | FazBrowse Home |