What is the difference between Association and Aggregation? [duplicate] - uml

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

How to Show Reference type and Object type separately for same object in UML object and sequence diagram

The diagram shows sample Class diagram and usage of objects of those classes in Sequence diagram.
In the above diagram instance myCar can be referred either by reference of ShowroomItem or reference of interface Vehicle. Accordingly the clients Driver/ SalesEngineer will get functionality access.
I agree that in implementation stage (e.g. Java), type identification is not required here and we will treat myCar as instance of base type (either interface) used itself.
But in sequence diagram, (for clarity) I am unable to indicate that the reference for myCar for Driver should be of Vehicle and for SalesEngineer should be of ShowroomItem.
I searched in UML 2.0 books, I did not get suitable notation. As per current understanding, I can show it either as "myCar : Vehicle" or "myCar : ShowroomItem", but that does not indicate that its Object of Car referred as Interface. This shortcomming does not enforce that playMusic can not work when referred as Vehcile.
Is there any notation to show this kind of detail?
As I am not satisfied with any answer provided, I am trying to add following to make question more clear, address some objections raised in the answers and proposing kind of solution for experts to review.
Looking at the comments, I feel either people did not get the core question, or I failed to highlight the core issue. First let me demonstrate code does not break. following code allows SalesEngineer to access Abstraction with sell() and buy() functionality and Driver to access Abstraction with only start() and stop() functionality [designed that way]. This is a strongest feature of interfaces to publish different abstractions to different clients. Java Collections use same multiple base types namely Object and Comparable in TreeSet, one for equals() and another for compare() on entities.
package com.se.stackoverflow;
interface Vehicle {
abstract void start();
abstract void stop();
}
interface ShowroomItem {
abstract void buy();
abstract void sell();
}
class Car implements ShowroomItem, Vehicle {
// **Car IS-A Vehicle and ShowroomItem BY-DEFINITION**
// **and as per SOLID principle interface segregation**
public void start() { System.out.println("Started");}
public void stop() { System.out.println("Stopped");}
public void sell() { System.out.println("Sold");}
public void buy() { System.out.println("Baught");}
}
class SalesEngineer {
private ShowroomItem item = null;
public SalesEngineer(ShowroomItem item) { this.item = item;}
public void doTransaction() {item.buy(); item.sell();}
}
class Driver {
private Vehicle veh = null;
public Driver(Vehicle veh) {this.veh = veh;}
public boolean testDrive() {veh.start(); veh.stop(); return true;}
}
public class ShowroomOwner {
public void makeDeal(Car carForDeal) {
Driver driver = new Driver(carForDeal);
SalesEngineer engineer = new SalesEngineer(carForDeal);
if (driver.testDrive()) {
engineer.doTransaction();
}
}
public static void main(String[] args) {
// simulates client as ShowroomOwner to save space
new ShowroomOwner().makeDeal(new Car());
}
}
After referring "UML 2 and Unified Process" by Jim Arlow, I found we can show changing states over life line in sequence diagrams. I feel similar notation we can use to show changing types object [i havnt seen this documented in UML anywhere but its my suggestion to UML group].
e.g. here myCar is Object of its class Car (class of object can never be changed) but its reference type varies as per the left side like ShowroomItem or Vehicle.
May be following sequence diagram can show it. [Example classes are just indicative to highlight auto type casting effects]
UML notation issue
You need to make choices about the type you want to show for each lifeline of a sequence diagram, because UML only allows a single one. Since myCar is a Car which implements Vehicle and ShowroomItem you may chose any of the 3 types.
Once the type chosen, UML has no way to provide an alternate view on the type in the same diagram. You can show the scenario with myCar being a Car. But the other lifelines must comply with the interface they know (provided no other usage dependency give them access to the full Car) and it's up to you to ensure consistency. This may be error prone, as you have demonstrated with playMusic().
You way address your concern with one or several notes in the diagram to remind the readers in plain text of the interface-related constraints. But a far better approach would be to keep it simple and show the interaction between SalesEngineer and Car and between Driver and Car in two separate diagrams. This is closer to the reality of your design, and promotes sound separation of concerns.
OOP Design issue
Qwerty_so and Bruno have already pointed to the weaknesses in your design. I fully agree with them. Indeed, a Car is a Vehicle. But a Car is not a ShowroomItem: a Car can temporarily have the role of a showroom item. Or converesely, a showroom item may correspond at a given time to a specific car.
If a car is not a showroom item it should neither inherit from such a class nor implement such an interface. Hence, prefer composition over inheritance, for example:
SalesEngineer trades in ShowroomItem
CarForSale implements ShowroomItem
CarForSale is associated to one Car
Driver drives a Vehicle (caution: bias towards rolling vehicles, because there's no driver on a plane ;-) )
Car implements Vehicle
Car can be associated to a CarForSale (but only if it is for sale by a SalesEngineer)
This design ensures better separation of concerns. For example, you can sell() or buy() only cars that are really for sale and not any car. Only cars for sale will have a price.
The other advantage is that you can show this full picture in a more robust way in a single sequence diagram since the different responsibilities are implemented by different objects.
First your class diagram is wrong, a car is not a ShowRoomItem, a car is the same before and after it is sail/buy, in your case the car will have to stop (may temporary) to be a ShowRoomItem since it is sail/buy. The fact it is a show room item is not a type but in the best case a state, but for me to have that state as an attribute of the car is a wrong choice too.
Second the actual instance the driver or sales engineer accesses is a car, and the car does not care who uses it, the radio does not disappear when the person is a sales engineer, so the car always accept to play radio if enough pre conditions are on (battery have power, may be key turn on etc)
The fact there are restrictions depending on who is the person must not be done at the level of the car, else this is out of the reality and fully artificial, but at the level of the person/role.
In UML for that kind of restrictions you can use constraints.
Since Car inherits (per your UML) from ShowRoomItem it will also have the sell() operation and the SalesEngineer can use it.
I think your model is just strange. A car which has a sell() operation is definitely one I would not buy. In other words: your class model is broken.

What UML relationship is in between class A and B, where A uses methods of B to create its instance and then uses it inside own (A's) class?

What UML relationship is in between class A and B, where A uses methods of B in order to create its instance and then uses it inside own (A's) class?
Is it a dependency? e.g A -----------> B
e.g how to depict relationship between Sender and Invite in the below code?
class Sender{
public void sendInvite(){
....
Invite i = Invite.getInstance();
....
}
}
class Invite{
...
public static Invite getInstance(){
...
}
}
Note: once we return from method sendInvite() we do not store any link to class Invite anymore.
In my opinion it could be expressed as one of the usage dependencies. Draw a dashed arrow from Sender to Invite, label it with «call» or something similar and move on
A (directed) association from Sender to Invite. Since you do not use a property but a local variable you must not use a role name for Invite. Further you likely have an association to self for Invite which (I guess) is used to retrieve the singleton instance inside getInstance().
From Superstructures 2.1.1 about Association
An association specifies a semantic relationship that can occur between typed instances. It has at least two ends represented by properties, each of which is connected to the type of the end. More than one end of the association may have the same type.
An end property of an association that is owned by an end class or that is a navigable owned end of the association indicates that the association is navigable from the opposite ends; otherwise, the association is not navigable from the opposite ends.
... and Dependency:
A dependency signifies a supplier/client relationship between model elements where the modification of the supplier may impact the client model elements. A dependency implies the semantics of the client is not complete without the supplier. The presence of dependency relationships in a model does not have any runtime semantics implications, it is all given in terms of the model-elements that participate in the relationship, not in terms of their instances.

How to represent a static relationship in an UML class diagram

I'm having trouble finding a good answer for how to represent a relationship between two classes A and B, where an instance of A is a static (class scope) variable in B. For example:
class A {
}
class B {
static A a;
}
I'm not even sure if it is a regular association or a dependency (or something else?).
One idea would be to use a stereotype on the role name of A in the relationship, but I have never seen that done. And since I understand that it is 'rule' not to use both an attribute and a relationship to represent the same member I can't either underline an attribute called 'a' (since I rather want to model the contents of the class A).
Just use a stereotype <<static>> to model static relationships or attributes

How to define this class relationship

This my UML class diagram (URL)
In above diagram, ChildParent (or Child1, Child2, and Child3) can only be initialized in MainObject->create_new_object() and store it in class Library through ObjectData->lib->add_object(key, newObject).
So, how to define UML class relationship between ChildParent, Library, and MainObject?
Thank you
Relationships between classes are structural, not behavioral. The MainObject is creating it, but it is not controlling its lifespan nor does it own it in any way. After creating is it handed over to the ObjectData, transported to the Library and stored there. There is a behavioral relationship between the MainObject and the ChildParent object, but there is not a structural relationship between the two of them. I should not depict any relationship between them.
The Library is storing it. This is a typical whole part relationship and structural. What is a library without books? Therefor would I make use of the aggregation type of relation. It is not the composition, because the Library does not control the lifespan of any ChildParent or Child object nor does it imply that the ChildObject will be destroyed when the Library object is destroyed. That might happen, but given the presented data is that not clear to me.
EDIT as a reply to a comment:
Class diagrams show the structural relationships between classes, not their usage. When a class implements an interface, then will you see that relationship in the diagram. In the code (the behaviour) might you not see this relationship, because the implementation is hidden in a factory method or provided by a IoC container or it might even be a relationship that is never used.
What is the relationship between a class (the caller) that is picking a class (the callee) from a library and between the caller and the library?
It is obvious that the caller and the library have a behavioral relationship. If the module changes, can the caller get his callee from some other class. Therefor will the library and the caller have no relationship in the class diagram.
There is a structural relationship between the caller and the callee. The caller needs the callee. Your comment does not specify the exact relationship between them, but there is a relationship. The weakest form is the dependency relationship. An example in connection with a library is that a person is lending a book from a library. When he starts to read the book, is the callee used. It does not belong intrinsically to the person as a whole, but it does belong to a certain method of the person class.
There are a lot of ways to implement a library. It can be for instance a wardrobe. What is the relationship between a person in the military and his uniforms? He needs to wear some uniforms in certain situations, yet in other situations are those uniforms forbidden to wear. Wearing an uniform is a part of the class military. You can not be in the military without wearing an uniform in the time of duty. The moment you are out of the military are you not allowed to wear the uniform anymore. Hence has a military a compositional relationship with that uniform from his wardrobe.
There are more types of relationships possible between the caller and the callee. You can not say it at forehand. You must answer it the same way as any other relationship. The first question is very clear: is this a structural relationship or not? Keywords like 'is a' and 'has a' depict a structural relationship. Keywords like 'uses', 'asks', 'picks from' show a behavioral relationship. Have you concluded that it is a structural relationship, then should you find out what the dependency between the two classes is.

UML association and dependency

What is the difference between association and dependency? Can you give code examples?
What is the relationship between class A and B?
class A
{
B *b;
void f ()
{
b = new B ();
b->f();
delete b;
}
}
The short answer is: how any specific source language construct should be represented in UML is not strictly defined. This would be part of a standardized UML profile for the language in question, but these are sadly few and far between. Long answer follows.
In your example, I'm afraid I would have to say "neither", just to be difficult. A has a member variable of type B, so the relationship is actually an aggregation or a composition... Or a directed association. In UML, a directed association with a named target role is semantically equivalent to an attribute with the corresponding name.
As a rule of thumb, it's an aggregation if b gets initialized in A's constructor; it's a composition if it also gets destroyed in B's destructor (shared lifecycle). If neither applies, it's an attribute / directed association.
If b was not a member variable in A, and the local variable b was not operatoed on (no methods were called on it), then I would represent that as a dependency: A needs B, but it doesn't have an attribute of that type.
But f() actually calls a method defined in B. This to me makes the correct relationship a <<use>>, which is a more specialized form of dependency.
Finally, an (undirected) association is the weakest form of link between two classes, and for that very reason I tend not to use them when describing source constructs. When I do, I usually use them when there are no direct source code relationships, but the two classes are still somehow related. An example of this might be a situation where the two are responsible for different parts of the same larger algorithm, but a third class uses them both.
It may be useful to see this question I asked: does an association imply a dependency in UML
My understanding is:
Association
public class SchoolClass{
/** This field, of type Bar, represents an association, a conceptual link
* between SchoolClass and Student. (Yes, this should probably be
* a List<Student>, but the array notation is clearer for the explanation)
*/
private Student[] students;
}
Dependency
public class SchoolClass{
private Timetable classTimetable;
public void generateTimetable(){
/*
* Here, SchoolClass depends on TimetableGenerator to function,
* but this doesn't represent a conceptual relationship. It's more of
* a logical implementation detail.
*/
TimetableGenerator timetableGen = new TimetableGenerator();
/*
* Timetable, however, is an association, as it is a conceptual
* relationship that describes some aspect of the data that the
* class holds (Remember OOP101? Objects consist of data and operations
* upon that data, associations are UMLs way or representing that data)
*/
classTimetable = timetableGen.generateTimetable();
}
}
If you want to see the difference at the "code level", in an association between A and B, the implementation of A (or B or both depending on cardinalities, navigability,...) in an OO lang would include an attribute of type B.
Instead in a dependency, A would probably have a method where one of the parameters is of type B. So A and B are not linked but changing B would affect the dependant class A since maybe the way the A method manipulates the object B is no longer valid (e.g. B has changed the signature of a method and this induces a compile error in the class A)
Get it from Wiki: Dependency is a weaker form of relationship which indicates that one class depends on another because it uses it at some point of time. One class depends on another if the latter is a parameter variable or local variable of a method of the former. This is different from an association, where an attribute of the former is an instance of the latter.
So I think the case here is association, if B is a parameter variable or local variable of a method of the A, then they are dependency.
A dependency really is very loosely defined. So there would be no code representation.
Wiki: A dependency is a semantic relationship where a change to the influent or independent modeling element may affect the semantics of the dependent modeling element.[1]
From the OMG Spec: A dependency is a relationship that signifies that a single or a set of model elements requires other model elements for their specification or implementation. This means that the complete semantics of the depending elements is either semantically or structurally dependent on the definition of the supplier element(s).

Resources