Choosing Between an Interface and an Abstract Class

   

Interfaces and abstract classes provide similar functionality, so it is important to know when to select one over the other as you design a system. In general, you should choose interfaces over abstract classes. The use of an interface separates your design from any implementation details. Even if you declare a purely abstract class without any method implementations , you must inherit from it to define classes that share the behavior defined by its methods . Given that Java only supports single inheritance, this requirement is a significant one. If you define your required method signatures in an interface instead, you place no restrictions on the class hierarchy in your system.

If you have default behavior that could be shared by several classes, you might be tempted to base your design on an abstract class instead of an interface. The main point to remember is that the two choices are not mutually exclusive. You can design using an interface and then provide a class that implements the default behavior that you need. This class can be an abstract implementation of the interface that you extend, or a collection of method implementations that you delegate a portion of the method responsibility to in your interface implementations. This latter approach is often preferred because it places no inheritance requirements on your class design.

The use of interfaces is not without its drawbacks, however. In particular, trying to change an interface after code has been developed with it is not always easy. If you add a method to an existing interface, every class that previously implemented it is now a compiler error waiting to happen. Each implementation must be updated to include any method additions or changes in method signature. Because of this, it is typically a better idea in this situation to create a new interface that extends the original one and adds any new methods that are now required. Code that depends on the new methods can be written to reference the new interface without impacting the existing implementations.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net