Java Reference
In-Depth Information
Summary
An interface is a specification that is meant to be implemented by classes. An interface may contain members that
are static constants, abstract methods, default methods, static methods, and nested types. An interface cannot have
instance variables. An interface cannot be instantiated.
An interface with no members is known as a market interface. An interface with only one abstract method is
known as a functional interface.
A class implements interfaces. The keyword
implements
is used in a class declaration to implement interfaces.
The class implementing an interface inherits all members from the interface, except the static methods. If the class
inherits abstract methods from the implemented interfaces, it needs to override them and provide an implementation
or it should declare itself abstract. The class-implementing interfaces are subtypes of the implemented interfaces and
the implemented interfaces are supertypes of the class. A class inherits the same methods from multiple supertypes
(superclasses or superinterfaces) with the same signature; in such a case, the method from the superclass takes
precedence; if all methods are inherited from superinterfaces, the most specific method is used; if there are still
multiple candidates, the class must override the method to resolve the conflict.
An interface may inherit from other interfaces. The keyword
extends
is used in the interface declaration to specify
all inherited interfaces. The interfaces from which the interface is inherited are known as superinterfaces and the
interface itself is known as a subinterface. A subinterface inherits all members of its superinterfaces, except their static
methods. A conflict may arise if an interface inherits a method combination default-default or default-abstract with the
same signature from multiple superinterfaces. The conflict is resolved in two steps: the most specific candidate is used;
if there are multiple most specific candidates, the interface must override the conflicting method.
Before Java 8, it was not possible, without breaking the code, to evolve interfaces after they are published. From
Java 8, you can add default and static methods to existing interfaces.
Dynamic binding is used when an abstract or default method is called using a variable of an interface type. Static
binding is used when the static methods of an interface is called. Note that the static methods of an interface can be
called using only one syntax.
InterfaceName.staticMethodName(arg1, arg2...)