Java – When to Use Inheritance or Composition/Aggregation?

class-designjavaobject-oriented-design

In general, how do I decide whether to use make a class a super class, or to make it a private data member of another class? For example, given two classes, how does one decide whether to do this:

public class Sprite {
    private BaseImage image;
    ...

or this:

public class Sprite extends BaseImage {
    ...

Functionally, I know the difference: in the second case, any method that uses an instance of the Sprite class will have access to the underlying BaseImage behavior. In the first case the behavior of the BaseImage object is hidden. But from a design perspective, which is preferable in what cases?

Best Answer

If i understand your question correctly (and i am not sure that i do), you are having a similiar issue than i had a few weeks ago.

Ask yourself whether Sprite has a baseImage [instance] or rather is a baseImage [subclass]

Further reading:

my own question
Is-a
has-a

If i got something wrong, just ignore this answer :)