Java Reference
In-Depth Information
An interface and all of its method headings are normally declared to be public.
They cannot be given private, protected, or package access. (The modifier
public
may be omitted, but all the methods will still be treated as if they are public.)
When a class implements an interface, it must make all the methods in the inter-
face public.
An interface is a type. This allows you to write a method with a parameter of an
interface type, such as a parameter of type
, and that parameter will accept as
an argument any class you later define that implements the interface.
An interface serves a function similar to a base class, but it is important to note
that it is not a base class. (In fact, it is not a class of any kind.) Some programming
languages (such as C++) allow one class to be a derived class of two or more differ-
ent base classes. This is not allowed in Java. In Java, a derived class can have only
one base class. However, in addition to any base class that a Java class may have, it
can also implement any number of interfaces. This allows Java programs to approx-
imate the power of multiple base classes without the complications that can arise
with multiple base classes.
You might want to say the argument to
Ordered
interface (Dis-
play 13.2) is the same as the class doing the implementation (for example,
in the
precedes
Ordered
). There is no way to say this in Java, so we normally make
OrderedHourlyEmployee
such parameters of type
. It would be legal to make the argument to
Object
precedes
of type
, but that is not normally preferable to using
as the param-
Ordered
Object
eter type. If you make the argument of type
, you would still have to han-
Ordered
dle the case of
and the case of an argument that (while
) is not of type
null
Ordered
.
An interface definition is stored in a
OrderedHourlyEmployee
file and compiled just as a class defini-
.java
tion is compiled.
Abstract Classes Implementing Interfaces
As you saw in the previous subsection, a concrete class (that is, a regular class) must
give definitions for all the method headings given in an interface in order to imple-
ment the interface. However, you can define an abstract class that implements an
interface but only gives definitions for some of the method headings given in the inter-
face. The method headings given in the interface that are not given definitions are
made into abstract methods. A simple example is given in Display 13.3.
Derived Interfaces
You can derive an interface from a base interface. This is often called
extending
extending an
interface
the interface. The details are similar to deriving a class. An example is given in
Display 13.4.
Search WWH ::




Custom Search