This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Stephan van Hulst wrote:Remember, abstract classes are for behaviour, interfaces are for types.
I don't really understand what you mean by this.
An interface defines a set of behaviors without specifying the details of those behaviors. An abstract class defines the details. But an abstract class also binds its implementing classes to its class hierarchy. Consider an interface Pourable and an abstract class Bottle. A class that implements Pourable can pour() without having to be a Bottle; it could be a PaintCan or a RainStorm instead. But a class that extends Bottle will have the benefit of inheriting all of Bottle's attributes and behaviors. We know, when we use a WineBottle, that everything that is true of Bottle is true of WineBottle. But when we use a Pourable, all we know is that it can pour(); we don't know how, and we don't know what, it is pouring.
So I would say: Use an abstract class as a foundation for a family of closely related objects with behaviors that may vary. Use an interface when the important thing is that a behavior exists, and it doesn't matter what thing is behaving.
What I mean by "type" is that interfaces should be used to define structures that you work with. By "behaviour" I mean the implementation of such a structure.
We're talking about the same thing, but the words I used might have been a bit confusing.
Anyway, I don't think you should use abstract classes as the base of a hierarchy unless it implements some interface. Actually, this goes for normal classes as well. Case in point: InputStream.
InputStream should have been an interface, with a separate AbstractInputStream class that provides the default implementation that the current InputStream class has.
Bottle is a useful starting point to implement a WineBottle, but we shouldn't have an abstract Bottle without also providing the "type" we care about: Pourable. We don't care about Bottle's "type". We only care about its "behaviour".
y'all covered it quite well. looking at it slightly differently. i can write a class that implements MouseListener and MouseMotionListener and have to write a bunch of do-nothing methods when instead i can use an abstract class(lucky me java supplies one) MouseAdapter. now i only have to write the methods i actually override.
I can think of one more widely used example - Using an abstract Data Access Object(DAO) class. You could code away the most simple and reusable methods like DB Insert/Fetch/Update/Delete in 1 abstract class and you could create separate interfaces for different tables. These interfaces would contain specific functions pertaining to that table. You could then create table wise implementations that would extend the same abstract class and implement table wise interfaces.