1

Consider we have two class named Point and Line. And Line class has two constructors. This is code of Point class.

// The Point class definition
public class Point {
   // Private member variables
   private int x, y;   // (x, y) co-ordinates

   // Constructors
   public Point(int x, int y) {
      this.x = x;
      this.y = y;
   }
   public Point() {    // default (no-arg) constructor
      x = 0;
      y = 0;
   }
}    

And this is code of Line class.

public class Line {
   // Private member variables
   Point begin, end;   // Declare begin and end as instances of Point

   // Constructors
   public Line(int x1, int y1, int x2, int y2) {
      begin = new Point(x1, y1);  
      end   = new Point(x2, y2);
   }`
   public Line(Point begin, Point end) {
      this.begin = begin;
      this.end   = end;
   }
}

As you see Line class has two constructor. And First constructor is example of Compositon while second constructor example aggregation. Now, what can we say about this case? Can a class have both aggregation and composition? Thank for your answers.

tsnorri
  • 1,966
  • 5
  • 21
  • 29
OmerArslan
  • 87
  • 1
  • 9
  • possible duplicate of [Implementation difference between Aggregation and Composition in Java](http://stackoverflow.com/questions/11881552/implementation-difference-between-aggregation-and-composition-in-java) – xmojmr Jan 13 '15 at 06:28

2 Answers2

3

A generally accepted definition of the difference between aggregation and composition is lifetime responsibility and ownership.

  • Aggregation: An object A holds references to other objects, but those other objects are shared with other classes. When A is disposed, the other objects continue to live and be used in the application
  • Composition: An object B is "made" of other objects. When A is disposed, so are the other objects.

It's worth quoting Fowler on this:

Few things in the UML cause more consternation than aggregation and composition

...

Aggregation (white diamond) has no semantics beyond that of a regular association. It is, as Jim Rumbaugh puts it, a modeling placebo

...

Composition (black diamond) does carry semantics. The most particular is that an object can only be the part of one composition relationship

So yes, a class can have both composition and aggregation relationships to the objects it holds references to, but possibly not as per the example you have shown.

Community
  • 1
  • 1
Andy Brown
  • 18,961
  • 3
  • 52
  • 62
0

Since the defining characteristic of composition (versus aggregation) is having exclusive/non-shareable parts (see https://stackoverflow.com/a/27889087/2795909), your example of a Point-Line part-whole relationship is clearly an aggregation (no matter if you pass the point objects to, or create them in, the constructor) since the two points definijng a line can be shared with other lines.

Community
  • 1
  • 1
Gerd Wagner
  • 5,481
  • 1
  • 22
  • 41