1

Possible Duplicate:
Inheritance vs. Aggregation

A parter in this site, told that I need 'aggregation over inheritance' as solution.

I have investigated what is each think, but 'over inheritance'? That's my doubt. Someone can show me example of what does it mean?

Thanks in advance.

Community
  • 1
  • 1
Darf Zon
  • 6,268
  • 20
  • 90
  • 149
  • 8
    Probably: Use Aggregation _instead of_ Inheritance. – H H Jun 29 '12 at 14:23
  • 1
    http://stackoverflow.com/questions/269496/inheritance-vs-aggregation – Dave Ziegler Jun 29 '12 at 14:23
  • A link to the previosu question would have helped. And consider activating an English spell checker for your Browser. – H H Jun 29 '12 at 14:24
  • I think Henk has it right, it means prefer aggregation over inheritance. Try to use aggregation instead of inheritance if it makes sense to. – SwDevMan81 Jun 29 '12 at 14:24
  • 2
    More commonly: "Favor Composition over Inheritance". – seldary Jun 29 '12 at 14:30
  • Beware of rules like this, inheritance can be better if the solution fits although generally composition is a better fit. Know the guidance and then make an informed decision about your solution. – joocer Jun 29 '12 at 14:36

3 Answers3

2

It means one class should contain an instance of another class instead of inheriting from it.

Example of inheritance

class Engine
{
}

class vehicle extends Engine
{
}

Example of aggregation

class Engine
{
}

class Vehicle
{
Engine powerplant;
}

I wrote a post about the dangers of poor inheritance examples in our textbooks. I found a helpful example in the way Federal Aviation Administration subdivides regulations based on how it classifies aircraft and their capabilities.

Kelly S. French
  • 12,198
  • 10
  • 63
  • 93
1

As mentioned in the comments, it means to use aggregation instead of inheritance when possible. A explanation is given in Prefer composition over inheritance?

Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type.

Difference between composition and aggregation if you want to know.

Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
1

Aggregation is less error prone then using inheritance (inheritance can lead to a difficult to maintain code, and difficult to understand)

Also you when you inherit a class you also expose all it's public members to clients of the derived class (you can instead use aggregation and make the field private to limit clients access to that object)

Rzv.im
  • 978
  • 7
  • 12