Interfaces in Java

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

An interface extends the concept of an abstract class. An interface consists of method declarations; however, no method body is included. An interface is a requirement: it specifies "what" without the "how." The "how" is left to the class that implements the interface. A class that implements an interface undertakes to implement all the methods in the interface. The signatures of the class methods must be the same as those in the interface.
PerformTransaction is an example of an interface with deposit and withdraw method declarations.


PerformTransaction
interface PerformTransaction
{
public void deposit (double amount);
public double withdraw (double amount);
}



Note that all methods in an interface are public by default; we have chosen to make this explicit. An interface is not a class, so we do not have a corresponding object. Any class can choose to implement the PerformTransaction interface where it makes sense to have deposit and withdraw methods. To implement an interface, include the implements interface_name keyword in the class declaration, for example,

class InvestmentFund implements PerformTransaction
{


Note that InvestmentFund must include both deposit and withdraw method bodies. The signatures of these methods must match with those in the interface. Failure to comply will cause a compilation error in the InvestmentFund class.

Interfaces provide a form of multiple inheritance since a class can choose to implement any number of interfaces. We shall see examples of this in Chapter 8 when discussing event- handling listener interfaces. Interfaces can include constants as well as methods. For example, we could add the following constants to the PerformTransaction interface:

static final int GOOD_CUSTOMER = 1;
static final int BAD_CUSTOMER = 0;


It is possible for an interface to define only constants and no methods.

No comments:

Post a Comment