What is the difference between association, aggregation and composition? - oop

What is the difference between association, aggregation, and composition?
Please explain in terms of implementation.

For two objects, Foo and Bar the relationships can be defined
Association - I have a relationship with an object. Foo uses Bar
public class Foo {
private Bar bar;
};
NB: See Fowler's definition - the key is that Bar is semantically related to Foo rather than just a dependency (like an int or string).
Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar
public class Foo {
private Bar bar = new Bar();
}
Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.
public class Foo {
private Bar bar;
Foo(Bar bar) {
this.bar = bar;
}
}

I know this question is tagged as C# but the concepts are pretty generic questions like this redirect here. So I am going to provide my point of view here (a bit biased from java point of view where I am more comfortable).
When we think of Object-oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words the object of one class may use services/methods provided by the object of another class. This kind of relationship is termed as association..
Aggregation and Composition are subsets of association meaning they are specific cases of association.
In both aggregation and composition object of one class "owns" object of another class.
But there is a subtle difference. In Composition the object of class that is owned by the object of it's owning class cannot live on it's own(Also called "death relationship"). It will always live as a part of it's owning object where as in Aggregation the dependent object is standalone and can exist even if the object of owning class is dead.
So in composition if owning object is garbage collected the owned object will also be which is not the case in aggregation.
Confused?
Composition Example : Consider the example of a Car and an engine that is very specific to that car (meaning it cannot be used in any other car). This type of relationship between Car and SpecificEngine class is called Composition. An object of the Car class cannot exist without an object of SpecificEngine class and object of SpecificEngine has no significance without Car class. To put in simple words Car class solely "owns" the SpecificEngine class.
Aggregation Example : Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning the Car object owns the Wheel object but we cannot say the Wheel object has no significance without the Car Object. It can very well be used in a Bike, Truck or different Cars Object.
Summing it up -
To sum it up association is a very generic term used to represent when a class uses the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.
More details here.
I am the author of http://opensourceforgeeks.blogspot.in and have added a link above to the relevant post for more context.

Association is generalized concept of relations. It includes both Composition and Aggregation.
Composition(mixture) is a way to wrap simple objects or data types into a single unit. Compositions are a critical building block of many basic data structures
Aggregation(The formation of a number of things into a cluster) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.
Trick to remember the difference :
"Has-A": Aggregation
"Part-Of": comPOsitoin
"Is-a": Inheritance
context
Aggregation
Composition
Life time
objects have their own lifetime and there is no owner
controlled by whole or parent that owns it
Scope
parent objects and child objects are independent
parent object also means the death of its children.
Relationship
Has-a
Part-of
Strength
weak relationship
strong relationship.
Real-life example
Car and Driver
Car and wheels
Now let observe the following image
Analogy:
Composition: The following picture is image composition i.e. using individual images making one image.
Aggregation : collection of image in single location
For example, A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.

Dependency (references)
It means there is no conceptual link between two objects. e.g. EnrollmentService object references Student & Course objects (as method parameters or return types)
public class EnrollmentService {
public void enroll(Student s, Course c){}
}
Association (has-a)
It means there is almost always a link between objects (they are associated).
Order object has a Customer object
public class Order {
private Customer customer
}
Aggregation (has-a + whole-part)
Special kind of association where there is whole-part relation between two objects. they might live without each other though.
public class PlayList {
private List<Song> songs;
}
OR
public class Computer {
private Monitor monitor;
}
Note: the trickiest part is to distinguish aggregation from normal association. Honestly, I think this is open to different interpretations.
Composition (has-a + whole-part + ownership)
Special kind of aggregation. An Apartment is composed of some Rooms. A Room cannot exist without an Apartment. when an apartment is deleted, all associated rooms are deleted as well.
public class Apartment{
private Room bedroom;
public Apartment() {
bedroom = new Room();
}
}

From a post by Robert Martin in comp.object:
Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.
//[Example:]
//|A|----------->|B|
class A
{
private:
B* itsB;
};
Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).
//[Example:]
//|Node|<>-------->|Node|
class Node
{
private:
vector<Node*> itsNodes;
};
The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.
Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.
//[Example:]
//|Car|<#>-------->|Carburetor|
class Car
{
public:
virtual ~Car() {delete itsCarb;}
private:
Carburetor* itsCarb
};

As others said, an association is a relationship between objects, aggregation and composition are types of association.
From an implementation point of view, an aggregation is obtained by having a class member by reference. For example, if class A aggregates an object of class B, you'll have something like this (in C++):
class A {
B & element;
// or B * element;
};
The semantics of aggregation is that when an object A is destroyed, the B object it is storing will still exists. When using composition, you have a stronger relationship, usually by storing the member by value:
class A {
B element;
};
Here, when an A object is destroyed, the B object it contains will be destroyed too. The easiest way to achieve this is by storing the member by value, but you could also use some smart pointer, or delete the member in the destructor:
class A {
std::auto_ptr<B> element;
};
class A {
B * element;
~A() {
delete B;
}
};
The important point is that in a composition, the container object owns the contained one, whereas in aggregation, it references it.

It's amazing how much confusion exists about the distinction between the three relationship concepts association, aggregation and composition.
Notice that the terms aggregation and composition have been used in the C++ community, probably for some time before they have been defined as special cases of association in UML Class Diagrams.
The main problem is the widespread and ongoing misunderstanding (even among expert software developers) that the concept of composition implies a life-cycle dependency between the whole and its parts such that the parts cannot exist without the whole, ignoring the fact that there are also cases of part-whole-associations with non-shareable parts where the parts can be detached from, and survive the destruction of, the whole.
As far as I can see, this confusion has two roots:
In the C++ community, the term "aggregation" was used in the sense of a class defining an attribute for referencing objects of another independent class (see, e.g., [1]), which is the sense of association in UML Class Diagrams. The term "composition" was used for classes that define component objects for their objects, such that on destruction of the composite object, these component objects are being destroyed as well.
In UML Class Diagrams, both "aggregation" and "composition" have been defined as special cases of associations representing part-whole relationships (which have been discussed in philosophy for a long time). In their definitions, the distinction between an "aggregation" and a "composition" is based on the fact if it allows sharing a part between two or more wholes. They define "compositions" as having non-shareable (exclusive) parts, while "aggregations" may share their parts. In addition they say something like the following: very often, but not in all cases, compositions come with a life-cycle dependency between the whole and its parts such that the parts cannot exist without the whole.
Thus, while UML has put the terms "aggregation" and "composition" in the right context (of part-whole relationships), they have not managed to define them in a clear and unambiguous manner, capturing the intuitions of developers. However, this is not surprising because there are so many different properties (and implementation nuances) these relationships can have, and developers do not agree on how to implement them.
See also my extended answer to the SO question of Apr 2009 listed below.
And the property that was assumed to define "composition" between OOP objects in the C++ community (and this belief is still widely held): the run-time life-cycle dependency between the two related objects (the composite and its component), is not really characteristic for "composition" because we can have such dependencies due to referential integrity also in other types of associations.
For instance, the following code pattern for "composition" was proposed in an SO answer:
final class Car {
private final Engine engine;
Car(EngineSpecs specs) {
engine = new Engine(specs);
}
void move() {
engine.work();
}
}
The respondent claimed that it would be characteristic for "composition" that no other class could reference/know the component. However, this is certainly not true for all possible cases of "composition". In particular, in the case of a car's engine, the maker of the car, possibly implemented with the help of another class, may have to reference the engine for being able to contact the car's owner whenever there is an issue with it.
[1] http://www.learncpp.com/cpp-tutorial/103-aggregation/
Appendix - Incomplete list of repeatedly asked questions about composition versus aggregation on StackOverflow
[Apr 2009]
Aggregation versus Composition [closed as primarily opinion-based by]
[Apr 2009]
What is the difference between Composition and Association relationship?
[May 2009]
Difference between association, aggregation and composition
[May 2009]
What is the difference between composition and aggregation? [duplicate]
[Oct 2009]
What is the difference between aggregation, composition and dependency? [marked as duplicate]
[Nov 2010]
Association vs. Aggregation [marked as duplicate]
[Aug 2012]
Implementation difference between Aggregation and Composition in Java
[Feb 2015]
UML - association or aggregation (simple code snippets)

Association
Association represents the relationship between two classes.It can be unidirectional(one way) or bidirectional(two way)
for example:
unidirectional
Customer places orders
bidirectional
A is married to B
B is married to A
Aggregation
Aggregation is a kind of association.But with specific features.Aggregation is the relationship in one larger "whole" class contains one or more smaller "parts" classes.Conversely, a smaller "part" class is a part of "whole" larger class.
for example:
club has members
A club("whole") is made up of several club members("parts").Member have life to outside the club. If the club("whole") were to die, members("parts") would not die with it. Because member can belong to multiple clubs("whole").
Composition
This is a stronger form of aggregation."Whole" is responsible for the creation or destruction of its "parts"
For example:
A school has departments
In this case school("whole") were to die, department("parts") would die with it.
Because each part can belong to only one "whole".

It's important to understand why we should even bother with using more than once relationship line. The most obvious reason is to describe parent-child relationship between classes (when parent deleted all its child’s are deleted as a result), but more impotently, we want to distinguish between simple association and composition in order to place implicit restrictions on the visibility and propagation of changes to the related classes, a matter which plays an important role in understanding and reducing system complexity.
Association
The most abstract way to describe static relationship between classes is using the Association link, which simply states that there is some kind of a link or a dependency between two classes or more.
Weak Association
ClassA may be linked to ClassB in order to show that one of its methods includes parameter of ClassB instance, or returns instance of ClassB.
Strong Association
ClassA may also be linked to ClassB in order to show that it holds a reference to ClassB instance.
Aggregation (Shared Association)
In cases where there’s a part-of relationship between ClassA (whole) and ClassB (part), we can be more specific and use the aggregation link instead of the association link, highlighting that ClassB can also be aggregated by other classes in the application (therefore aggregation is also known as shared association).
It’s important to note that the aggregation link doesn’t state in any way that ClassA owns ClassB nor that there’s a parent-child relationship (when parent deleted all its child’s are being deleted as a result) between the two. Actually, quite the opposite! The aggregation link usually used to stress the point that ClassA is not the exclusive container of ClassB, as in fact ClassB has another container.
Aggregation v.s. Association
The association link can replace the aggregation link in every situation, while aggregation cannot replace association in situations where there’s only a ‘weak link’ between the classes, i.e. ClassA has method/s that contain parameter of ClassB but ClassA doesn’t hold reference to ClassB instance.
Martin Fowler suggest that the aggregation link should not be used at all because it has no added value and it disturb consistency, Quoting Jim Rumbaugh "Think of it as a modeling placebo".
Composition (Not-Shared Association)
We should be more specific and use the composition link in cases where in addition to the part-of relationship between ClassA and ClassB - there’s a strong lifecycle dependency between the two, meaning that when ClassA is deleted then ClassB is also deleted as a result
The composition link shows that a class (container, whole) has exclusive ownership over other class/s (parts), meaning that the container object and its parts constitute a parent-child/s relationship.
Unlike association and aggregation, when using the composition relationship, the composed class cannot appear as a return type or parameter type of the composite class. Thus, changes to the composed class cannot propagate to the rest of the system. Consequently, usage of composition limits complexity growth as the system grows.
Measuring system complexity
System complexity can be measured simply by looking at a UML class diagram and evaluating the association, aggregation, and composition relationship lines. The way to measure complexity is to determine how many classes can be affected by changing a particular class. If class A exposes class B, then any given class that uses class A can theoretically be affected by changes to class B. The sum of the number of potentially affected classes for every class in the system is the total system complexity.
You can read more on my blog:
http://aviadezra.blogspot.com/2009/05/uml-association-aggregation-composition.html

Composition (If you remove "whole", “part” is also removed automatically– “Ownership”)
Create objects of your existing class inside the new class. This is called composition because the new class is composed of objects of existing classes.
Typically use normal member variables.
Can use pointer values if the composition class automatically handles allocation/deallocation responsible for creation/destruction of subclasses.
Composition in C++
#include <iostream>
using namespace std;
/********************** Engine Class ******************/
class Engine
{
int nEngineNumber;
public:
Engine(int nEngineNo);
~Engine(void);
};
Engine::Engine(int nEngineNo)
{
cout<<" Engine :: Constructor " <<endl;
}
Engine::~Engine(void)
{
cout<<" Engine :: Destructor " <<endl;
}
/********************** Car Class ******************/
class Car
{
int nCarColorNumber;
int nCarModelNumber;
Engine objEngine;
public:
Car (int, int,int);
~Car(void);
};
Car::Car(int nModelNo,int nColorNo, int nEngineNo):
nCarModelNumber(nModelNo),nCarColorNumber(nColorNo),objEngine(nEngineNo)
{
cout<<" Car :: Constructor " <<endl;
}
Car::~Car(void)
{
cout<<" Car :: Destructor " <<endl;
Car
Engine
Figure 1 : Composition
}
/********************** Bus Class ******************/
class Bus
{
int nBusColorNumber;
int nBusModelNumber;
Engine* ptrEngine;
public:
Bus(int,int,int);
~Bus(void);
};
Bus::Bus(int nModelNo,int nColorNo, int nEngineNo):
nBusModelNumber(nModelNo),nBusColorNumber(nColorNo)
{
ptrEngine = new Engine(nEngineNo);
cout<<" Bus :: Constructor " <<endl;
}
Bus::~Bus(void)
{
cout<<" Bus :: Destructor " <<endl;
delete ptrEngine;
}
/********************** Main Function ******************/
int main()
{
freopen ("InstallationDump.Log", "w", stdout);
cout<<"--------------- Start Of Program --------------------"<<endl;
// Composition using simple Engine in a car object
{
cout<<"------------- Inside Car Block ------------------"<<endl;
Car objCar (1, 2,3);
}
cout<<"------------- Out of Car Block ------------------"<<endl;
// Composition using pointer of Engine in a Bus object
{
cout<<"------------- Inside Bus Block ------------------"<<endl;
Bus objBus(11, 22,33);
}
cout<<"------------- Out of Bus Block ------------------"<<endl;
cout<<"--------------- End Of Program --------------------"<<endl;
fclose (stdout);
}
Output
--------------- Start Of Program --------------------
------------- Inside Car Block ------------------
Engine :: Constructor
Car :: Constructor
Car :: Destructor
Engine :: Destructor
------------- Out of Car Block ------------------
------------- Inside Bus Block ------------------
Engine :: Constructor
Bus :: Constructor
Bus :: Destructor
Engine :: Destructor
------------- Out of Bus Block ------------------
--------------- End Of Program --------------------
Aggregation (If you remove "whole", “Part” can exist – “ No Ownership”)
An aggregation is a specific type of composition where no ownership between the complex object and the subobjects is implied. When an aggregate is destroyed, the subobjects are not destroyed.
Typically use pointer variables/reference variable that point to an object that lives outside the scope of the aggregate class
Can use reference values that point to an object that lives outside the scope of the aggregate class
Not responsible for creating/destroying subclasses
Aggregation Code in C++
#include <iostream>
#include <string>
using namespace std;
/********************** Teacher Class ******************/
class Teacher
{
private:
string m_strName;
public:
Teacher(string strName);
~Teacher(void);
string GetName();
};
Teacher::Teacher(string strName) : m_strName(strName)
{
cout<<" Teacher :: Constructor --- Teacher Name :: "<<m_strName<<endl;
}
Teacher::~Teacher(void)
{
cout<<" Teacher :: Destructor --- Teacher Name :: "<<m_strName<<endl;
}
string Teacher::GetName()
{
return m_strName;
}
/********************** Department Class ******************/
class Department
{
private:
Teacher *m_pcTeacher;
Teacher& m_refTeacher;
public:
Department(Teacher *pcTeacher, Teacher& objTeacher);
~Department(void);
};
Department::Department(Teacher *pcTeacher, Teacher& objTeacher)
: m_pcTeacher(pcTeacher), m_refTeacher(objTeacher)
{
cout<<" Department :: Constructor " <<endl;
}
Department::~Department(void)
{
cout<<" Department :: Destructor " <<endl;
}
/********************** Main Function ******************/
int main()
{
freopen ("InstallationDump.Log", "w", stdout);
cout<<"--------------- Start Of Program --------------------"<<endl;
{
// Create a teacher outside the scope of the Department
Teacher objTeacher("Reference Teacher");
Teacher *pTeacher = new Teacher("Pointer Teacher"); // create a teacher
{
cout<<"------------- Inside Block ------------------"<<endl;
// Create a department and use the constructor parameter to pass the teacher to it.
Department cDept(pTeacher,objTeacher);
Department
Teacher
Figure 2: Aggregation
} // cDept goes out of scope here and is destroyed
cout<<"------------- Out of Block ------------------"<<endl;
// pTeacher still exists here because cDept did not destroy it
delete pTeacher;
}
cout<<"--------------- End Of Program --------------------"<<endl;
fclose (stdout);
}
Output
--------------- Start Of Program --------------------
Teacher :: Constructor --- Teacher Name :: Reference Teacher
Teacher :: Constructor --- Teacher Name :: Pointer Teacher
------------- Inside Block ------------------
Department :: Constructor
Department :: Destructor
------------- Out of Block ------------------
Teacher :: Destructor --- Teacher Name :: Pointer Teacher
Teacher :: Destructor --- Teacher Name :: Reference Teacher
--------------- End Of Program --------------------

Problem with these answers is they are half the story: they explain that aggregation and composition are forms of association, but they don't say if it is possible for an association to be neither of those.
I gather based on some brief readings of many posts on SO and some UML docs that there are 4 main concrete forms of class association:
composition: A is-composed-of-a B; B doesn't exist without A, like a room in a home
aggregation: A has-a B; B can exist without A, like a student in a classroom
dependency: A uses-a B; no lifecycle dependency between A and B, like a method call parameter, return value, or a temporary created during a method call
generalization: A is-a B
When a relationship between two entities isn't one of these, it can just be called "an association" in the generic sense of the term, and further described other ways (note, stereotype, etc).
My guess is that the "generic association" is intended to be used primarily in two circumstances:
when the specifics of a relationship are still being worked out; such relationship in a diagram should be converted as soon as possible to what it actually is/will be (one of the other 4).
when a relationship doesn't match any of those 4 predetermined by UML; the "generic" association still gives you a way of representing a relationship that is "not one of the other ones", so that you aren't stuck using an incorrect relationship with a note "this is not actually aggregation, it's just that UML doesn't have any other symbol we could use"

Association, Aggregation, Composition
Association, Aggregation, Composition are about Has a relationship.
Aggregation and Composition are subsets of Association which describe relationship more accurately
Aggregation - independent relationship. An object can be passed and saved inside class via constructor, method, setter...
Composition - dependent relationship. An object is created by owner object
*Association is an alternative for sybtyping

Simple rules:
A "owns" B = Composition : B has no meaning or purpose in the system
without A
A "uses" B = Aggregation : B exists independently (conceptually) from A
A "belongs/Have" B= Association; And B exists just have a relation
Example 1:
A Company is an aggregation of Employees.
A Company is a composition of Accounts. When a Company ceases to do
business its Accounts cease to exist but its People continue to exist.
Employees have association relationship with each other.
Example 2: (very simplified)
A Text Editor owns a Buffer (composition). A Text Editor uses a File
(aggregation). When the Text Editor is closed,
the Buffer is destroyed but the File itself is not destroyed.

https://www.linkedin.com/pulse/types-relationships-object-oriented-programming-oop-sarah-el-dawody/
Composition: is a "part-of" relationship.
for example “engine is part of the car”, “heart is part of the body”.
Association: is a “has-a” type relationship
For example, suppose we have two classes then these two classes are said to be “has-a” relationships if both of these entities share each other’s object for some work and at the same time they can exist without each other's dependency or both have their own lifetime.
The above example showing an association relationship because of both Employee and Manager class using the object of each other and both their own independent life cycle.
Aggregation: is based is on "has-a" relationship and it's is \\a special form of association
for example, “Student” and “address”. Each student must have an address so the relationship between Student class and Address class will be “Has-A” type relationship but vice versa is not true.

I think this link will do your homework: http://ootips.org/uml-hasa.html
To understand the terms I remember an example in my early programming days:
If you have a 'chess board' object that contains 'box' objects that is composition because if the 'chess board' is deleted there is no reason for the boxes to exist anymore.
If you have a 'square' object that have a 'color' object and the square gets deleted the 'color' object may still exist, that is aggregation
Both of them are associations, the main difference is conceptual

Composition:
This is where once you destroy an object (School), another object (Classrooms) which is bound to it would get destroyed too. Both of them can't exist independently.
Aggregation:
This is sorta the exact opposite of the above (Composition) association where once you kill an object (Company), the other object (Employees) which is bound to it can exist on its own.
Association.
Composition and Aggregation are the two forms of association.

From: Remo H. Jansen book “Beginning React: Learning TypeScript 2.x - Second Edition” :
We call association those relationships whose objects have an independent life cycle where there is no ownership of the objects. Let's take a look at an example of a teacher and a student. Multiple students can be associated with a single teacher, and a single student can be associated with multiple teachers, but both have independent life cycles (both can create and delete independently). So, when a teacher leaves the school, we don't need to delete any students, and when a student leaves the school, we don't need to delete any teachers.
We call aggregation those relationships whose objects have an independent life cycle, but there is ownership, and child objects cannot belong to another parent object. Let's take an example of a cell phone and a cell phone battery. A single battery can belong to a phone, but if the phone stops working, and we delete it from our database, the phone battery will not be deleted because it may still be functional. So, in aggregation, while there is ownership, objects have their life cycle
We use the term composition to refer to relationships whose objects don't have an independent life cycle, and if the parent object is deleted, all child objects will also be deleted. Let's take an example of the relationship between questions and answers. Single questions can have multiple answers, and answers cannot belong to multiple questions. If we delete questions, answers will automatically be deleted.

In a very simple sentence:
Aggregation and Composition are subsets of association.
A uses B -> this is an aggregation
A needs B -> is composition.
Read more here.

Association is a relationship between two separate classes and the association can be of any type say one to one, one to may etc. It joins two entirely separate entities.
Aggregation is a special form of association which is a unidirectional one way relationship between classes (or entities), for e.g. Wallet and Money classes. Wallet has Money but money doesn’t need to have Wallet necessarily so its a one directional relationship. In this relationship both the entries can survive if other one ends. In our example if Wallet class is not present, it does not mean that the Money class cannot exist.
Composition is a restricted form of Aggregation in which two entities (or you can say classes) are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live and a heart needs a Human body to survive. In other words when the classes (entities) are dependent on each other and their life span are same (if one dies then another one too) then its a composition. Heart class has no sense if Human class is not present.

I'd like to illustrate how the three terms are implemented in Rails. ActiveRecord calls any type of relationship between two models an association. One would not find very often the terms composition and aggregation, when reading documentation or articles, related to ActiveRecord. An association is created by adding one of the association class macros to the body of the class. Some of these macros are belongs_to, has_one, has_many etc..
If we want to set up a composition or aggregation, we need to add belongs_to to the owned model (also called child) and has_one or has_many to the owning model (also called parent). Wether we set up composition or aggregation depends on the options we pass to the belongs_to call in the child model. Prior to Rails 5, setting up belongs_to without any options created an aggregation, the child could exist without a parent. If we wanted a composition, we needed to explicitly declare this by adding the option required: true:
class Room < ActiveRecord::Base
belongs_to :house, required: true
end
In Rails 5 this was changed. Now, declaring a belongs_to association creates a composition by default, the child cannot exist without a parent. So the above example can be re-written as:
class Room < ApplicationRecord
belongs_to :house
end
If we want to allow the child object to exist without a parent, we need to declare this explicitly via the option optional
class Product < ApplicationRecord
belongs_to :category, optional: true
end

in OOP, classes are related to each other. It means their instances call methods from each other. So, if instances of a class call methods from another class, they are related and generally we model this relationship with ASSOCIATION.
For example in the following code snippet, the Customer class is associated with the Order class. she/he cancels the orders.
class Customer {
private Order[] orders;
public boolean removeCart() {
for (int i = 0 ; i < orders.length ; i++) {
orders[i].cancel();
}
}
}
AGGREGATION means a class has some instances of another class. it's nothing more than association and Martin Fowler suggests not using it. Because when a class is associated with another class it has a reference to that class to invoke the methods on it.
But COMPOSITION is a meaningful subset of association. It means a class is composed of some other classes. For example we have a Student class composed of some other classes like ReportCard. We know that the report card is strongly dependent to the student and if we remove the student from the system, their report card should be removed too.

Related

Store a reference to component class in compositional relationship

I'm looking at composition. What does it mean to 'store a reference to a component'?
To me this means that there will be two classes, and that one class will be instantiated from within the other class. Is this correct? How else could you represent a compositional relationship?
How would this particular example be different from an aggregation? (or would that require an object storing reference to instantiated classes created out of it's scope..)
i.e. (Ruby syntax)
class A
def initialize
#stuff
end
end
class B
def initialize
#many_a_instances = []
end
def attach_an_A
#many_a_instances << A.new
end
end
Would it be a better to define class A within class B?
In light of thunderous enthusiasm from would be question answerers... the answer is this (based on conversation with colleagues and friends):
How you define classes is somewhat independent of the relationship between instances of different classes (which is a dependent on how classes are instantiated).
If an instance defines a reference to an instance, then the referenced instance's lifespan is dependant on the object that holds the reference. This defines a compositional relationship.
However, if you instantiated an object and then passed a reference to that object to another class, that would be an example of aggregation. Because the lifespan of the two instantiated objects is independent from each other, but one object still references the other.
So same classes, but different relationships between instances. and in terms of where classes are defined, that will probably be use-case specific.
Any better answer will be marked as accepted over this one :)

difference between unidirectional association and dependency

According to wikipedia
Dependency is a relationship that shows that an element, or set of elements, requires other model elements for their specification or implementation.[1] The element is dependent upon the independent element, called the supplier.
So is it not the same as unidirectional association?
Do we use dependency when an operation in one class uses object of the other class as its parameter?
How are unidirectional association and dependency different.
Any example would be very helpful
Dependency :
Indicates that a client element(of any kind, including classes,
packages, use cases, etc) has knowledge of another supplier element,
and a change in supplier can effect the client.
So "dependency" is very broad relationship.Suppose that if a class-object(client) has another class-object(supplier) as a member,if a class-object send a message to another class-object,if a class-object takes another class-object as an parameter from its methods, even if a class(client) is subclass of another class(supplier) there will be dependency since change from supplier will effect clients.
Technically all of those relationships can be shown by "Dependency" line. But some of above relationships already has special notations: such as for superclass-subclass relationship we have generalization relationship.No need to show also "dependency" line because if they have generalization relationship, they have dependency. And we have "association" relationship for class-object(client) who has another class-object as a member [attribute]. So also no need to show extra dependency line in this situation.
Actually "Dependency" is badly defined relationship for class diagrams. But it can be usefull for showing dependency in which UML has no special notation such as :
if you has another class-object(supplier) as a parameter in one of your class(client) methods
if you have dependency to global variables
when you call static methods on another classes.
local variables (which you think you have important dependency)
public class RepositoryManager
{
public UpdatePriceFor(ProductDescription description)
{
Time date = Clock::GetTime();
Money oldPrice =description.GetPrice();
...
}
private IList<Item> itemsList = new List<Item>();
}
So all "associations" are also shows "dependency".But "dependency" is
broad-general-weak relationship.As a rule if there is a special
relationship which is more specific-stronger than dependency
relationship than use it. And lastly use all your relationship
"economically". Show only important ones based on modeler-model reader
perspectives.
[ Source : Adapted from Craig Larman's Applying UML and Patterns book ]
Check Fowlers bliki for further information DependencyAndAssociation
Association means that the two associated entities are linked semantically. Dependency only declares that there is a... well, dependency of some sort. All associations are dependencies, while a dependency does not actually mean association. For example, class 'A' depends on class 'B' if it has a method that takes 'B' and passes it as argument to a function in another class. But if 'A' calls some method of class 'B', it should be modeled as association.
Disclaimer I have read the UML specification and also asked myself this question a number of times. I arrived at at the definition above, but I'm still not sure it is 100% correct.

How to decide whether use IS A or HAS A Relation

public class B {
public String getMe()
{
return "Some";
}
}
Assume that i have a above class , by which parameters should we decide what to use ?? Whether is a or Has a Relation ??
HAS - A
public class A {
public static void main(String args[])
{
B b = new B();
System.out.println(b.getMe());
}
}
or
public class A extends B
{
public static void main(String args[])
{
A b = new A();
System.out.println(b.getMe());
}
}
Depends on the logical relation. It just needs to make sense.
Example:
Lets say you have Animal classes.
So you have these classes: Animal, Dog, Cat , Leopard, Fur, Feet
Cat and Dog IS A Animal.
Leopard IS A Cat.
Animal HAS A Fur, Feet.
In a nutshell:
IS A relationship means you inherit and extend the functionality of the base class.
HAS A relationship means the class is using another class, so it has it as a member.
There are 4 types of relations possible :
Generalization (IS A) : Which is implemented using inheritance like you did above. It's used when class A has all the same feature of B and you want to add some more features. So you simply extend B and add the new features.
Aggregation (HAS A) : This is a bit weaker relation than generalization. You use this relation when the object of A owns objects of B or is composed of objects of B (may be among other objects of other classes). The first type is called shared aggregation, the second is called composition. In aggregation and composition there usually an object controlling the life of the other object (it instantiates it and destroys it as it needs).
Association: In association, the classes simply know about each other's so it's weaker than aggregation. The objects do not control each other's life.
Usage : It's the weakest relation of two classes and it means simply that one class may appear as a type in a method parameter or is used internally in code.
In your example, it should be aggregation (HAS A) if A has a field of type B. But if it just creates instance of B to be used in code internally and the object is disposed from memory when the scope ends then it's neither IS A nor HAS A. It's just a usage relation.
In simple term:
"is a" represent the inheritence/extends
"has a" represents the delegation/association
for example:
House is a Building (inheritance)
House has a door(s) (association)
Here is one of the best resources I used for understanding OOP: http://chortle.ccsu.edu/CS151/cs151java.html (part 6 & 10)
is-a is like for example, a Dog is an Animal or a Cat is an Animal or It is like "a person is that-kind of a person". Is-a relationships have other objects' properties, like here "Animal" is a class(object) and etc.
The has-a relationship is like, an object has its own properties, for example, Fish has Gills or pants have pockets ... something like that.

Difference between object and instance

I know this sort of question has been asked before, but I still feel that the answer is too ambiguous for me (and, by extension, some/most beginners) to grasp.
I have been trying to teach myself broader concepts of programming than procedural and basic OOP. I understand the concrete concepts of OOP (you make a class that has data (members) and functions (methods) and then instantiate that class at run time to actually do stuff, that kind of thing).
I think I have a handle on what a class is (sort of a design blueprint for an instance to be created in its likeness at compile time). But if that's the case, what is an object? I also know that in prototype based languages, this can muck things up even more, but perhaps this is why there needs to be a clear distinction between object and instance in my mind.
Beyond that, I struggle with the concepts of "object" and "instance". A lot of resources that I read (including answers at SO) say that they are largely the same and that the difference is in semantics. Other people say that there is a true conceptual difference between the two.
Can the experts here at SO help a beginner have that "aha" moment to move forward in the world of OOP?
Note: this isn't homework, I don't go to school - however, I think it would help people that are looking for homework help.
A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance.
The truth is that object oriented programming often creates confusion by creating a disconnect between the philosophical side of development and the actual mechanical workings of the computer. I'll try to contrast the two for you:
The basic concept of OOP is this: Class >> Object >> Instance.
The class = the blue print.
The Object is an actual thing that is built based on the 'blue print' (like the house).
An instance is a virtual copy (but not a real copy) of the object.
The more technical explanation of an 'instance' is that it is a 'memory reference' or a reference variable. This means that an 'instance' is a variable in memory that only has a memory address of an object in it. The object it addresses is the same object the instance is said to be 'an instance of'. If you have many instances of an object, you really just have many variables in difference places in your memory that all have the same exact memory address in it - which are all the address of the same exact object. You can't ever 'change' an instance, although it looks like you can in your code. What you really do when you 'change' an instance is you change the original object directly. Electronically, the processor goes through one extra place in memory (the reference variable/instance) before it changes the data of the original object.
The process is: processor >> memory location of instance >> memory location of original object.
Note that it doesn't matter which instance you use - the end result will always be the same. ALL the instances will continue to maintain the same exact information in their memory locations - the object's memory address - and only the object will change.
The relationship between class and object is a bit more confusing, although philosophically its the easiest to understand (blue print >> house). If the object is actual data that is held somewhere in memory, what is 'class'? It turns out that mechanically the object is an exact copy of the class. So the class is just another variable somewhere else in memory that holds the same exact information that the object does. Note the difference between the relationships:
Object is a copy of the class.
Instance is a variable that holds the memory address of the object.
You can also have multiple objects of the same class and then multiple instances of each of those objects. In these cases, each object's set of instances are equivalent in value, but the instances between objects are not. For example:
Let Class A
From Class A let Object1, Object2, and Object3.
//Object1 has the same exact value as object2 and object3, but are in different places in memory.
from Object1>> let obj1_Instance1, obj1_Instace2 , obj1_Instance3
//all of these instances are also equivalent in value and in different places in memory. Their values = Object1.MemoryAddress.
etc.
Things get messier when you start introducing types. Here's an example using types from c#:
//assume class Person exists
Person john = new Person();
Actually, this code is easier to analyze if you break it down into two parts:
Person john;
john = new Person();
In technical speak, the first line 'declares a variable of type Person. But what does that mean?? The general explanation is that I now have an empty variable that can only hold a Person object. But wait a minute - its an empty variable! There is nothing in that variables memory location. It turns out that 'types' are mechanically meaningless. Types were originally invented as a way to manage data and nothing else. Even when you declare primitive types such as int, str, chr (w/o initializing it), nothing happens within the computer. This weird syntactical aspect of programming is part of where people get the idea that classes are the blueprint of objects. OOP's have gotten even more confusing with types with delegate types, event handlers, etc. I would try not focus on them too much and just remember that they are all a misnomer. Nothing changes with the variable until its either becomes an object or is set to a memory address of an object.
The second line is also a bit confusing because it does two things at once:
The right side "new Person()" is evaluated first. It creates a new copy of the Person class - that is, it creates a new object.
The left side "john =", is then evaluated after that. It turns john into a reference variable giving it the memory address of the object that was just created on the right side of the same line.
If you want to become a good developer, its important to understand that no computer environment ever works based on philosophic ideals. Computers aren't even that logical - they're really just a big collection of wires that are glued together using basic boolean circuits (mostly NAND and OR).
The word Class comes from Classification (A Category into which something is put), Now we have all heard that a Class is like a Blueprint,but what does this exactly mean ? It means that the Class holds a Description of a particular Category ,(I would like to show the difference between Class , Object and Instance with example using Java and I would request the readers to visualise it like a Story while reading it , and if you are not familiar with java doesn't matter) So let us start with make a Category called HumanBeing , so the Java program will expressed it as follows
class HumanBeing{
/*We will slowly build this category*/
}
Now what attributes does a HumanBeing have in general Name,Age,Height,Weight for now let us limit our self to these four attributes, let us add it to our Category
class HumanBeing{
private String Name;
private int Age;
private float Height;
private float Weight;
/*We still need to add methods*/
}
Now every category has a behaviour for example category Dog has a behaviour to bark,fetch,roll etc... , Similarly our category HumanBeing can also have certain behaviour,for example when we ask our HumanBeing what is your name/age/weight/height? It should give us its name/age/weight/height, so in java we do it as follows
class HumanBeing{
private String Name;
private int Age;
private float Height;
private float Weight;
public HumanBeing(String Name,int Age,float Height,float Weight){
this.Name = Name;
this.Age = Age;
this.Height = Height;
this.Weight = Weight;
}
public String getName(){
return this.Name;
}
public int getAge(){
return this.age;
}
public float getHeight(){
return this.Height;
}
public float getWeight(){
return this.Weight;
}
}
Now we have added behaviour to our category HumanBeing,so we can ask for its name ,age ,height ,weight but whom will you ask these details from , because class HumanBeing is just a category , it is a blueprint for example an Architect makes a blueprint on a paper of the building he wants to build , now we cannot go on live in the blueprint(its description of the building) we can only live in the building once it is built
So here we need to make a humanbeing from our category which we have described above , so how do we do that in Java
class Birth{
public static void main(String [] args){
HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);
}
}
Now in the above example we have created our first human being with name age height weight , so what exactly is happening in the above code? . We are Instantiating our category HumanBeing i.e An Object of our class is created
Note : Object and Instance are not Synonyms In some cases it seems like Object and Instance are Synonyms but they are not, I will give both cases
Case 1: Object and Instance seems to be Synonyms
Let me elaborate a bit , when we say HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90); An Object of our category is created on the heap memory and some address is allocated to it , and firstHuman holds a reference to that address, now this Object is An Object of HumanBeing and also An Instance of HumanBeing.
Here it seems like Objects and Instance are Synonyms,I will repeat myself they are not synonyms
Let Us Resume our Story , we have created our firstHuman , now we can ask his name,age,height,weight , this is how we do it in Java
class Birth{
public static void main(String [] args){
HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);
System.out.println(firstHuman.getName());
System.out.println(firstHuman.getAge());
...
...
}
}
so we have first human being and lets move feather by give our first human being some qualification ,let's make him a Doctor , so we need a category called Doctor and give our Doctor some behaviour ,so in java we do as follows
class Doctor extends HumanBeing{
public Doctor(String Name,int Age,float Height,float Weight){
super(Name,Age,Height,Weight);
}
public void doOperation(){
/* Do some Operation*/
}
public void doConsultation(){
/* Do so Consultation*/
}
}
Here we have used the concept of Inheritance which is bringing some reusability in the code , Every Doctor will always be a HumanBeing first , so A Doctor will have Name,Age,Weight,Height which will be Inherited from HumanBeing instead of writing it again , note that we have just written a description of a doctor we have not yet created one , so let us create a Doctor in our class Birth
class Birth{
public static void main(String [] args){
Doctor firstDoctor = new Doctor("Strange",40,6,80);
.......
.......
/*Assume some method calls , use of behaviour*/
.......
.......
}
}
Case 2: Object and Instance are not Synonyms
In the above code we can visualise that we are Instantiating our category Doctor and bringing it to life i.e we are simply creating an Object of the category Doctor , As we already know Object are created on Heap Memory and firstDoctor holds a reference to that Object on the heap ;
This particular Object firstDoctor is as follows (please note firstDoctor holds a reference to the object , it is not the object itself)
firstDoctor is An Object of class Doctor And An Instance of A class Doctor
firstDoctor is Not An Object of class HumanBeing But An Instance of class HumanBeing
So a particular Object can be an instance to a particular class but it need not be an object of that given class
Conclusion:
An Object is said to be an Instance of a particular Category if it satisfies all the characteristic of that particular Category
Real world example will be as follows , we are first born as Humans so image us as Object of Human , now when we grow up we take up responsibilities and learn new skills and play different roles in life example Son, brother, a daughter, father ,mother now What are we actually?We can say that we are Objects of Human But Instances of Brother,daughter,...,etc
I hope this helps
Thank You
Objects are things in memory while instances are things that reference to them. In the above pic:
std(instance) -> Student Object (right)
std1(instance) -> Student Object (left)
std2(instance) -> Student Object (left)
std3(instance) -> no object (null)
An object is an instance of a class (for class based languages).
I think this is the simplest explanation I can come up with.
A class defines an object. You can go even further in many languages and say an interface defines common attributes and methods between objects.
An object is something that can represent something in the real world. When you want the object to actually represent something in the real world that object must be instantiated. Instantiation means you must define the characteristics (attributes) of this specific object, usually through a constructor.
Once you have defined these characteristics you now have an instance of an object.
Hope this clears things up.
"A class describes a set of objects called its instances." - The Xerox learning Research Group, "The Smalltalk-80 System", Byte Magazine Volume 06 Number 08, p39, 1981.
What is an Object ?
An object is an instance of a class. Object can best be understood by finding real world examples around you. You desk, your laptop, your car all are good real world examples of an object.
Real world object share two characteristics, they all have state and behaviour. Humans are also a good example of an object, We humans have state/attributes - name, height, weight and behavior - walk, run, talk, sleep, code :P.
What is a Class ?
A class is a blueprint or a template that describes the details of an object. These details are viz
name
attributes/state
operations/methods
class Car
{
int speed = 0;
int gear = 1;
void changeGear(int newGear)
{
gear = newGear;
}
void speedUp(int increment)
{
speed = speed + increment;
}
void applyBrakes(int decrement)
{
speed = speed - decrement;
}
}
Consider the above example, the fields speed and gear will represent the state of the object, and methods changeGear, speedUp and applyBrakes define the behaviour of the Car object with the outside world.
References:
What is an Object ?
What is a Class ?
I think that it is important to point out that there are generally two things. The blueprint and the copies. People tend to name these different things; classes, objects, instances are just some of the names that people use for them. The important thing is that there is the blueprint and copies of it - regardless of the names for them. If you already have the understanding for these two, just avoid the other things that are confusing you.
Lets compare apples to apples. We all know what an apple is. What it looks like. What it tastes like. That is a class. It is the definition of a thing. It is what we know about a thing.
Now go find an apple. That is an instance. We can see it. We can taste it. We can do things with it. It is what we have.
Class = What we know about something. A definition.
Object/Instance = Something that fits that definition that we have and can do things with.
In some cases, the term "object" may be used to describe an instance, but in other cases it's used to describe a reference to an instance. The term "instance" only refers to the actual instance.
For example, a List may be described as a collection of objects, but what it actually holds are references to object instances.
I have always liked the idea that equals the definition of a class as that of an "Abstract Data Type". That is, when you defined a class you're are defining a new type of "something", his data type representation, in terms of primitives and other "somethings", and his behavior in terms of functions and/or methods. (Sorry for the generality and formalism)
Whenever you defined a class you open a new possibility for defining certain entities with its properties and behavior, when you instantiate and/or create a particular object out of it you're actually materializing that possibility.
Sometimes the terms object and instances are interchangeable. Some OOP purists will maintain that everything is an object, I will not complain, but in the real OOP world, we developers use two concepts:
Class: Abstract Data Type sample from which you can derive other ADT and create objects.
Objects: Also called instances, represents particular examples of the data structures and functions represented by a given Abstract Data Type.
Object Oriented Programming is a system metaphor that helps you organize the knowledge your program needs to handle, in a way that will make it easier for you to develop your program. When you choose to program using OOP you pick up your OOP-Googles, and you decide that you will see the problem of the real world as many objects collaborating between themselves, by sending messages. Instead of seeing a Guy driving a Car you see a Guy sending a message to the car indicating what he wants the car to do. The car is a big object, and will respond to that message by sending a message to it's engine or it's wheel to be able to respond properly to what the Driver told him to do in the message, etc...
After you've created your system metaphor, and you are seeing all the reality as objects sending messages, you decide to put all the things your are seeing that are relevant to your problem domain in the PC. There you notice that there are a lot of Guys driving different cards, and it's senseless to program the behavior of each one of them separately because they all behave in the same way... So you can say two things:
All those guys behave in the same way, so I'll create a class called
Driver that will specify who all the Drivers in the world behave,
because they all behave in the same way. (And your are using class based OOP)
Or your could say Hey! The second Driver behaves in the same way as the first Driver, except he likes going a little faster. And the third Driver behaves in the same way as the first Driver, except he likes zigzagging when he drives. (And you use prototype based OOP).
Then you start putting in the computer the information of how all the Drivers behave (or how the first driver behave, and how the second and third differ from that one), and after a while you have your program, and you use the code to create three drivers that are the model you are using inside that PC to refeer to the drivers you saw in the real world. Those 3 drivers that you created inside the PC are instances of either the prototype ( actually the first one is the prototype, the first one might be the prototype himself depending on how you model things) or the class that you created.
The difference between instance and object is that object is the metaphor you use in the real world. You choose to see the guy and the car as objects (It would be incorrect to say that you see them as instances) collaborating between themselves. And then you use it as inspiration to create your code. The instance only exists in your program, after you've created the prototype or the class. The "objects" exist outside the PC because its the mapping you use to unite the real world with the program. It unites the Guy with the instance of Driver you created in the PC. So object and instance are extremely related, but they are not exactly the same (an instance is a "leg" of an object in the program, and the other "leg" is in the real world).
I guess the best answer has already been given away.
Classes are blueprints, and objects are buildings or examples of that blueprint did the trick for me as well.
Sometimes, I'd like to think that classes are templates (like in MS Word), while objects are the documents that use the template.
Extending one of the earlier given examples in this thread...
Consider a scenario - There is a requirement that 5 houses need to be built in a neighbourhood for residential purposes. All 5 houses share a common construction architecture.
The construction architecture is a class.
House is an object.
Each house with people staying in it is an instance.

What is the difference between Composition and Association relationship?

In OOP, what is the difference between composition (denoted by filled diamond in UML) and association (denoted by empty diamond in UML) relationship between classes. I'm a bit confused. What is aggregation? Can I have a convincing real world example?
COMPOSITION
Imagine a software firm that is composed of different Business Units (or departments) like Storage BU, Networking BU. Automobile BU. The life time of these Business Units is governed by the lifetime of the organization. In other words, these Business Units cannot exist independently without the firm. This is COMPOSITION. (ie the firm is COMPOSED OF business units)
ASSOCIATION
The software firm may have external caterers serving food to the employees. These caterers are NOT PART OF the firm. However, they are ASSOCIATED with the firm. The caterers can exist even if our software firm is closed down. They may serve another firm! Thus the lifetime of caterers is not governed by the lifetime of the software firm. This is typical ASSOCIATION
AGGREGATION
Consider a Car manufacturing unit. We can think of Car as a whole entity and Car Wheel as part of the Car. (at this point, it may look like composition..hold on) The wheel can be created weeks ahead of time, and it can sit in a warehouse before being placed on a car during assembly. In this example, the Wheel class's instance clearly lives independently of the Car class's instance.
Thus, unlike composition, in aggregation, life cycles of the objects involved are not tightly coupled.
Here go a few examples:
I am an employee of a company, hence I am associated to that company. I am not part of it, nor do I compose it, but am related to it, however.
I am composed of organs, which unless are transplanted, will die with me. This is composition, which is a very strong bind between objects. Basically objects are composed by other objects. The verb says everything.
There is also another less bound kind of composition, called aggregation. An aggregation is when objects are composed by other objects, but their life cycles are not necessarily tied. Using an extreme example, a Lego toy is an aggregation of parts. Even though the toy can be dismantled, its parts can be recombined to make a different toy.
Owning and using.
Composition: the object with the reference owns the object referred to, and is responsible for its "lifetime", its destruction (and often creation, though it may be passed in). Also known as a has-a relationship.
Association: the object with the reference uses the object referred to, may not be an exclusive user, and isn't responsible for he referred-to object's lifetime. Also known as a uses-a relationship.
The OP comments:
Can you provide a real world example. Also, what is aggregation? – Marc
Aggregation: an Association that is from whole to part, and that can't be cyclic.
Examples:
Composition: a Car has-an Engine, a Person has-an Address. Basically, must have, controls lifetime.
Association: A Car has-a Driver, some class instance has-an ErrorLogger. Lifetime not controlled, may be shared.
Aggregation: A DOM (Document Object Model, that is the objects that make up a tree of HTML elements) Node has-a (an array of) child Nodes. The Node is top (well, higher) level; it "contains" its children, they don't contain it.
I believe that a code-based example can help to illustrate the concepts given by the above responses.
import java.util.ArrayList;
public final class AssoCia
{
public static void main( String args[] )
{
B b = new B();
ArrayList<C> cs = new ArrayList();
A a = new A( b, cs );
a.addC( new C() );
a.addC( new C() );
a.addC( new C() );
a.listC();
}
}
class A
{
// Association -
// this instance has a object of other class
// as a member of the class.
private B b;
// Association/Aggregation -
// this instance has a collection of objects
// of other class and this collection is a
// member of this class
private ArrayList<C> cs;
private D d;
public A(B b, ArrayList<C> cs)
{
// Association
this.b = b;
// Association/Aggregation
this.cs = cs;
// Association/Composition -
// this instance is responsible for creating
// the instance of the object of the
// other class. Therefore, when this instance
// is liberated from the memory, the object of
// the other class is liberated, too.
this.d = new D();
}
// Dependency -
// only this method needs the object
// of the other class.
public void addC( C c )
{
cs.add( c );
}
public void listC()
{
for ( C c : cs )
{
System.out.println( c );
}
}
}
class B {}
class C {}
class D {}
Independent existence.
An Invoice is composed of line items.
What's a line item that's not on an invoice? It's -- well -- it's nothing. It can't exist independently.
On the other hand, an Invoice is associated with a Customer.
Customer has an independent existence, with or without an invoice.
If the two things have independent existence, they may be associated.
If one thing cannot exist independently, then it is part of a composition.
Usually, composition means that the lifetime of the contained object is bounded by that of the container, whereas association is a reference to an object which may exist independently.
However, this is just the practice I've observed. I hate to admit it, but ploughing through the UML2 spec isn't high on my list of fun stuff to do!
Composition is a stricter relationship than aggregation. Composition means that something is so strongly related to something else that they cannot basically exist independently, or if they can, they live in different contexts.
Real world example: you define a GUI window, and then a text field where to write something.
Between the class defining the GUI and the class defining the text field there's composition. Together, they compose a widget which can be seen as an entity on its own. Suppose you delete the window, and you delete the text field as well.
Aggregation is different, in the sense that the link between the two entities is temporary, unstable, and occasional. A real world example. Suppose you have a database of objects containing multiple data instances. Now you run some filter to collect the data instances obeying a given criterium, and the resulting instances are pushed into a graphical list so that the user can see them. When the graphical widget receives the objects, it can form an aggregation of these entities, and present them. If the user closes the window with the graphical list, and the latter get deleted, the data objects should not be deleted. Maybe they are displayed somewhere else, or you still need them.
Also, in general, composition is defined at creation time. Aggregation is instead defined later in the object lifetime.
Composition means a part of the entity state is encapsulated by another type but it is conceptualy part of the entity state. For example you may have a address type and a employee entity type that includes a address.
Association means that a entity type is assocciated with another entity type but the assocciated entity is conceptualy not part of the entity state. For example a employee may be assocciated with a company.