Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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 :)

share|improve this answer
    
On one side, you ask to check if subclass is-a relation with superclass. On the other side, designers say that inheritance break encapsulation here. What is this dilemma? Do we follow is-a and has-a rule or avoid the disadvantages due to inheritance? –  overexchange Jun 15 at 4:26

In layman's words:

The first example is a "has a" relationship whereas the second one is an "is a relationship".

You don't have Car extend Wheel. Car has wheels.

Car doesn't have a Vehicle, Car is a Vechicle.

Inheritance is for "is a" relationships.

Composition is for "has a" relationships.

I don't know whether Sprite is a BaseImage or has a BaseImage. That's for you to decide.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.