Java Reference
In-Depth Information
Interfaces vs. abstract classes
An interface is used to enforce a type contract between the caller and an object.
An abstract class is used to provide a common parent, for behavior or interface,
for a set of child classes. In general, interfaces provide a more flexible, general,
and accurate mechanism for enforcing a type contract, whereas abstract classes
provide a better mechanism for sharing partial implementation. Interfaces pro-
vide equivalent functionality to C ++ multiple inheritance or Smalltalk mix-ins
and must be used if you want to capture default implementations.
Here are some general guidelines to follow:
Interfaces should be used whenever an implementation might change.
Abstract classes can lock in an implementation.
Interfaces should be used to describe add-on features ( Printable , Seri-
alizeable , Cloneable ).
Interfaces should be used when no default implementation is specified.
Abstract classes should be used when partial implementations are specified.
Interfaces can sometimes be combined with an abstract class providing a
fixed interface that can be used in a mix-in with a partial implementa-
tion. This combination can give you the convenience of a partial imple-
mentation with the full flexibility of an interface.
In the spirit of our continued refactoring of the bulletin board application, our
command architecture can ideally be captured as a reusable interface. The last
examples in chapter 6 can easily be modified to use a command interface. All
of the command objects already use a common interface; we need only
enforce them. To do so, we first define the command interface. Then, we can
enforce this interface across the classes that use it with the implements key-
word, as in listing 9.4.
Listing 9.4
Refactoring command objects
This program refactors our command objects to use interfaces. Then, our designs will be reus-
able, and the consistency will be enforced.
public interface Command { o Interface definition
public void initialize();
public void execute();
}
o Enforcement of
interface definition
public class AddPostCommand implements Command {
// code remains the same
}
Search WWH ::




Custom Search