3

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?

Tulains Córdova
39.6k13 gold badges102 silver badges157 bronze badges
asked Jun 22, 2013 at 13:40

2 Answers 2

1

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

answered Jun 22, 2013 at 14:33
1
  • 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? Commented Jun 15, 2015 at 4:26
3

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.

answered Jun 22, 2013 at 14:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.