views:

345

answers:

2

Hi, I know about Association and Aggregation and Composition and Generalization what they are by definition. inheritance is "is a" relationship and composition is "has a" relationship.

Class A {
}

Class B extends A { // this is Generalization
}

Class C {
 A ob;  // this is composition
}

now my question is how the Aggregation and simple Association is shown in terms of Programming code. ?

A: 

I'm not sure exactly what you're going for here, but I would suggest the following examples:

Aggregation

public class A { }
public class List<A> { }  // aggregation of A

Association (uses)

public class A
{
    public void AMethod() { ... }

public class B
{
    public void BMethod( A a )
    {
         a.AMethod();  // B uses A
    }
}
tvanfosson
+1  A: 

I suspect your real question has to do with composition versus aggregation. You can think of the difference in terms of ownership but the real distinction (for my money) is what controls the lifecycle of aggregated object.

In composition. when the composed object is destroyed its contained parts or classes are destroyed along with it. With aggregation, the contained object's lifetime can be independent of the containing object. In code. this comes down to whether the component object is specified by value or reference. Aggregation has to be done by reference (or pointer as in the example). If it is done by value the component part will go out of scope and be destroyed with containing object and is thus composition.

So in this case Engine is an example of composition and Battery an example of Aggregation.

#include <iostream>

using namespace std;

class Engine
{
   public:

      Engine() {cout << "Engine created\n";};
     ~Engine() {cout << "Engine destroyed\n";};
};


class Battery
{
   public:

      Battery() {cout << "Battery created\n\n";};
     ~Battery() {cout << "\nBattery destroyed\n";};
};

class Car
{
   private:

      Battery *bat;
      Engine  eng;  //Engine will go out of scope with Car

   public:

      Car(Battery* b) : bat(b) {cout << "Car created\n";};
     ~Car() {cout << "Car destroyed\n";};

       void drive(int miles) {/*...*/};
};



int main(int argc, char *argv[])
{
   //a Battery lifecycle exists independently of a car
   Battery* battery = new Battery();

   //but a car needs to aggregate a Battery to run
   Car* car1 = new Car(battery);

   car1->drive(5);

   //car1 and its Engine destroyed but not the Battery
   delete car1;

   cout << "---------------\n";

   //new car, new composed Engine, same old Battery
   Car* car2 = new Car(battery);

   car2->drive(5);
   delete car2;

   //destroy battery independently of the cars
   delete battery;

}

Apologies if this is not the best example but hopefully it illustrates the main point.

Duck