Java Reference
In-Depth Information
The body of the abstract method is always represented by a semicolon, not by a pair of braces. The following snippet
of code declares an interface named
Player
:
public interface Player {
public abstract void play();
public abstract void stop();
public abstract void forward();
public abstract void rewind();
}
The
Player
interface has four methods:
play()
,
stop()
,
forward()
, and
rewind()
. The
Player
interface
is a specification for an audio/video player. A real player, for example, a DVD player, will provide the concrete
implementation of the specification by implementing all four methods of the
Player
interface.
Use of the
abstract
and
public
keywords in a method declaration in an interface is redundant, even though
allowed by the compiler, because a method in an interface is implicitly
abstract
and
public
. The above declaration
of the
Player
interface can be rewritten as follows without changing its meaning:
public interface Player {
void play();
void stop();
void forward();
void rewind();
}
Abstract method declarations in an interface may include parameters, a return type, and a
throws
clause.
The following snippet of code declares an
ATM
interface. It declares four methods. If the account information
is wrong, the
login()
method throws an
AccountNotFoundException
. The
withdraw()
method throws an
InsufficientBalanceException
when the user attempts to withdraw an amount, which will reduce the balance to an
amount lower than the required minimum balance amount.
public interface ATM {
boolean login(int account) throws AccountNotFoundException;
boolean deposit(double amount);
boolean withdraw(double amount) throws InsufficientBalanceException;
double getBalance();
}
Abstract methods of an interface are inherited by classes that implement the interface, and classes override
them to provide an implementation. This implies that an abstract method in an interface cannot be declared
final
as the
final
keyword in a method declaration indicates that the method is final and it cannot be overridden.
However, a class may declare the overridden method of an interface
final
indicating that the subclasses cannot
override the method.
Static Methods Declarations
Let's refer to the code for the
Walkables
class shown in Listing 17-4. It is a utility class that contains a static method
called
letThemWalk()
. Creating such a utility class for providing static methods for working with an interface was
common prior to Java 8. You will find a number of interface/utility-class pairs in the Java library, for example,
Collection/Collections
,
Path/Paths
,
Channel/Channels
,
Executor/Executors
, etc. Following this convention,
you named your interface/utility-class pair as
Walkable/Walkables
. Java designers realized the necessity of the extra