Java Reference
In-Depth Information
4.6. When to Use Interfaces
An interface defines a type with an abstract contract. An abstract class
also defines a type with an abstract contract. Which should you use and
when?
There are two major differences between interfaces and abstract classes:
Interfaces provide a form of multiple inheritance, because you can
implement multiple interfaces. A class can extend only one other
class, even if that class has only abstract methods.
An abstract class can have a partial implementation, protected
parts, static methods, and so on, whereas interfaces are limited to
public constants and public methods with no implementation.
These differences usually direct the choice of which tool is best to use in
a particular implementation. If multiple inheritance is important or even
useful, interfaces are used. However, an abstract class enables you to
provide some or all of the implementation so that it can be inherited eas-
ily, rather than by explicit forwarding. Additionally, an abstract class can
control the implementation of certain methods by making them final for
example, our SortDouble class in Chapter 3 ensures that sorting is done
correctly. However, if you find yourself writing an abstract class with all
abstract methods, you're really writing an interface.
Any major class you expect to be extended, whether abstract or not,
should be an implementation of an interface. Although this approach re-
quires a little more work on your part, it enables a whole category of use
that is otherwise precluded. For example, suppose we had created an At-
tributed class instead of an Attributed interface with an AttributedImpl im-
plementation class. In that case, programmers who wanted to create new
classes that extended other existing classes could never use Attributed ,
since you can extend only one classthe class AttributedBody could nev-
er have been created. Because Attributed is an interface, programmers
have a choice: They can extend AttributedImpl directly and avoid the for-
warding, or, if they cannot extend, they can at least use composition and
 
Search WWH ::




Custom Search