Java Reference
In-Depth Information
Chapter 9. Interfaces
An interface declaration introduces a new reference type whose members are classes, inter-
faces, constants, and abstract methods. This type has no implementation, but otherwise un-
related classes can implement it by providing implementations for its abstract methods.
A
nested interface
is any interface whose declaration occurs within the body of another class
or interface.
A
top level interface
is an interface that is not a nested interface.
We distinguish between two kinds of interfaces - normal interfaces and annotation types.
This chapter discusses the common semantics of all interfaces - normal interfaces, both top
level (§
7.6
) and nested (§
8.5
, §
9.5
), and annotation types (§
9.6
)
. Details that are specific to
particular kinds of interfaces are discussed in the sections dedicated to these constructs.
Programs can use interfaces to make it unnecessary for related classes to share a common
abstract
superclass or to add methods to
Object
.
An interface may be declared to be a
direct extension
of one or more other interfaces, mean-
ing that it implicitly specifies all the member types, abstract methods, and constants of the
interfaces it extends, except for any member types and constants that it may hide.
A class may be declared to
directly implement
one or more interfaces, meaning that any in-
stance of the class implements all the
abstract
methods specified by the interface or interfaces.
A class necessarily implements all the interfaces that its direct superclasses and direct su-
perinterfaces do. This (multiple) interface inheritance allows objects to support (multiple)
common behaviors without sharing any implementation.
A variable whose declared type is an interface type may have as its value a reference to any
instance of a class which implements the specified interface. It is not sufficient that the class
happen to implement all the
abstract
methods of the interface; the class or one of its super-
classes must actually be declared to implement the interface, or else the class is not con-
sidered to implement the interface.
9.1. Interface Declarations
An
interface declaration
specifies a new named reference type. There are two kinds of in-