Store a reference to component class in compositional relationship - composition

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 :)

Related

How to mimic simple inheritance with base and child class constructors in Lua (Tutorial)

How to mimic simple inheritance with parent and child class constructors in Lua?
I will provide and accept and answer and would greatly appreciate if you commented on it or edited interesting information into it.
This is a guide for mimicking basic parent/child class inheritance in Lua.
I assume that basic features and syntax of Lua are known to the reader. The following statements are especially important:
There are no classes or objects in Lua, just tables.
A table can have a metatable.
If the metatable mt of a table t contains the __index metamethod (thus mt.__index), access to a non-existent key in t is attempted to be resolved via what's assigned to mt.__index.
If t calls a function t.foo() like this t:foo() then t itself is passed to foo() as the first argument called self. Inside the function, t itself is accessible as self.
Base class
Code
Base = {}
function Base:new(name)
Base.__index = Base
local obj = {}
setmetatable(obj, Base)
obj.name = name
return obj
end
function Base:sayName()
print(self.name..": My name is "..self.name..".")
end
Because of what the function Base:new(name) does, Base can now be seen as a new class, with Base:new(name) being its constructor. Remember that Base really is a table that sits somewhere in memory, not some abstract "class blue print". It contains a function Base:sayName(). This is what we could call a method with respect to OOP lingo.
But how does Base:new(name) let Base act like a class?
Explanation
Base.__index = Base
The Base table gets an __index metamethod, namely itself. Whenever Base is used as a metatable, searches to a non-existent index will be redirected to... Base itself. (Wait for it.) The line could also be written as self.__index = self, because Base calls :new(name) and thus self is Base therein. I prefer the first version, because it clearly shows what's happening. Also, Base.__index = Base could go outside of Base:new(name), however, I prefer having all the "set up" happen inside one scope (the "constructor") for the sake of clarity.
local obj = {}
setmetatable(obj, Base)
obj is created as a new empty table. It will become what we think of as an object of the "class" Base. The Base is now the metatable of obj. Since Base has an __index, access to non-existent keys in obj well be redirected to what is assigned to Base.__index. And since Base.__index is Base itself, access to non-existent keys in obj will be redirected to Base (where it would find Base:sayName(), for instance)!
obj.name = name
return obj
The obj (!) gets a new entry, a member, to which the constructor parameter is assigned. The obj is then returned and is what we would interpret as an object of class Base.
Demonstration
b = Base:new("Mr. Base")
b:sayName()
This prints "Mr. Base: My name is Mr. Base." as expected. b finds sayName() via the metatable-__index mechanism as described above, because it doesn't have such a key. sayName() lives inside Base (the "class table") and name inside b (the "object table").
Child class
Code
Child = {}
function Child:new(name, age) -- our child class takes a second argument
Child.__index = Child
setmetatable(Child, {__index = Base}) -- this is different!
local obj = Base:new(name, age) -- this is different!
setmetatable(obj, Child)
obj.age = age
return obj
end
function Child:sayAge()
print(self.name..": I am "..tonumber(self.age).." years old.")
end
The code is almost exactly the same as for the base class! Adding a second parameter in the Child:new(name, age) (i.e. the constructor) is not especially noteworthy. Base could also have had more than one parameter. However, the second and third line inside Child:new(name, age) were added and that is what causes Child to "inherit" from Base.
Note that Base may contain Base.__index, which makes it useful when used as a metatable, but that it has no metatable itself.
Explanation
setmetatable(Child, {__index = Base})
In this line, we assign a metatable to the Child class table. This metatable contains an __index metamethod, which is set to the Base class table. Thus, the Child class table will try to resolve access to non-existent keys via the Base class table. Thus, the Child class table has access to all of its own and all of Base's methods!
local obj = Base:new(name, age)
setmetatable(obj, Child)
In the first line, a new Base object table is created. At this point, its __index metamethod points to the Base class table. However, right in line two, its metatable is assigned to the Child class table. The reason why obj does not lose access to Base class methods lies in the fact that we redirected non-successful key accesses in Child to Base (by giving Child the proper metatable) just before! Since obj was created as a Base object table, it contains all of its members. Additionally, it also contains the members of a Child object table (once they are added in the Child:new(name, age) "constructor". It finds the methods of the Child class table via its own metamethod. And it finds the methods in the Base class table via the metamethod in the Child class table.
Note: With "Base object table" I mean the table that is returned by Base:new(name). With "Base class table" I mean the actual Base table. Remember, there are no classes/objects in Lua! The Base class table and the Base object table together mimic what we think of as OOP behavior. The same goes for Child, of course.
Also, scoping the assignment of Child's metatable inside Child:new(name, age) allows us to call Base's "constructor" and pass the name argument to it!
Demonstration
c = Child:new("Mrs. Child", 42)
c:sayName()
c:sayAge()
This prints "Mrs. Child: My name is Mrs. Child." and "Mrs. Child: I am 42 years old." as expected.
Conclusion
The sections above described how to implement OOP behavior in Lua. It is important to understand that
Base methods live inside the Base class table
Base members live inside the Base object table returned by Base:new()
Child methods live inside the Child class table
Child members live inside the Child object table returned by Child:new()
Referencing the correct tables is accomplished by the table's metatables.
All class tables assign themselves to their __index key. When used as metatables, they refer to themselves (i.e. where the class methods live). There is only one class table per "class".
Base classes don't have a metatable. They are used as metatables.
Child class tables also have a metatable, namely {__index = Base} (which redirects calls to the Base class table, i.e. where the Base class methods live).
All object tables assign their corresponding class tables as metatables. Since the class tables have set their __index metamethod, calls to the object tables can be redirected to the class tables where the class methods live. If it is a child class table (which means it also has a metatable), the redirection can happen even further. There can be arbitrarily many object tables.
Use the image above to follow along: What happens if a Child object table c tries to access a Base method, e.g. c:sayName()? Well: Has c a sayName() key? No. Does it have a metatable? Yes: Child (the Child class table). Does Child have an __index metamethod? Yes. Where does it point? To Child itself. Does Child have a sayName() key? No. Does Child have a metatable? Yes. Does it have an __index metamethod? Yes. Where does it point? To the Base class table. Does it have a sayName() key? Yes! :-)
Note
I am no Lua expert! I have only done some scripting in Lua so far, but over the last days I tried to wrap my mind around this. I found a lot of different, sometimes confusing solutions and finally arrived at this, which I would call the most simple but transparent solution. If you find any errors or caveats do not hesitate to comment!

When can a reference's type differ from the type of its object?

Yesterday I was asked a question in an interview:
Suppose class A is a base class, and class B is derived class.
Is it possible to create object of:
class B = new class A?
class A = new class B?
If yes, then what happen?
Objects of type B are guaranteed to also be objects of type A. This type of relationship is called "Is-a," or inheritance, and in OOP it's a standard way of getting polymorphism. For example, if objects of type A have a method foo(), objects of type B must also provide it, but its behavior is allowed to differ.
The reverse is not necessarily true: an object of type A (the base class) won't always be an object of type B (the derived class). Even if it is, this can't be guaranteed at compile-time, so what happens for your first line is that the code will fail to compile.
What the second line does depends on the language, but generally
Using a reference with the base type will restrict you to only accessing only members which the base type is guaranteed to have.
In Java, if member names are "hidden" (A.x exists and so does B.x, but they have different values), when you try to access the member you will get the value which corresponds to the type of the reference rather than the type of the object.
The code in your second example is standard practice when you are more interested in an API than its implementation, and want to make your code as generic as possible. For instance, often in Java one writes things like List<Integer> list = new ArrayList<Integer>(). If you decide to use a linked list implementation later, you will not have to change any code which uses list.
Take a look at this related question: What does Base b2 = new Child(); signify?
Normally, automatic conversions are allowed down the hierarchy, but not up. That is, you can automatically convert a derived class to its base class, but not the reverse. So only your second example is possible. class A = new class B should be ok since the derived class B can be converted to the base class A. But class B = new class A will not work automatically, but may be implemented by supplying an explicit conversion (overloading the constructor).
A is super class and B is a SubClass/Derived Class
the Statement
class A = new class B is always possible and it is called Upcasting because you are going Up in terms of more specific to more General
Example:
Fruit class is a Base Class and Apple Class is Derived
we can that Apple is more specific and must possess all the quality of an Fruit
so you can always do UPcasting where as
DownCasting is not always possible because Apple a=new Fruit();
A fruit can be a Apple or may it is not

What is the difference between an Instance and an Object?

What is the difference between an Instance and an Object?
Is there a difference or not?
The Instance and Object are from Object Oriented Programming.
For some programming languages like Java, C++, and Smalltalk, it is important to describe and understand code. In other languages that used in Structured Programming, this concept doesn't exist.
This is a view from Structural Programming. There's no real significant difference that should consume too much of your time. There might be some fancy language that some people might take up a lot of spaces to write about, but at the end of the day, as far as a coder, developer, programmer, architect, is concerned, an instance of a class and an object mean the same thing and can often be used interchangeably. I have never met anyone in my career that would be picky and spend a half-hour trying to point out the differences because there's really none. Time can be better spent on other development efforts.
UPDATE With regards to Swift, this is what Apple who invented Swift prefers :
An instance of a class is traditionally known as an object. However,
Swift classes and structures are much closer in functionality than in
other languages, and much of this chapter describes functionality that
can apply to instances of either a class or a structure type. Because
of this, the more general term instance is used.
Excellent question.
I'll explain it in the simplest way possible:
Say you have 5 apples in your basket. Each of those apples is an object of type Apple, which has some characteristics (i.e. big, round, grows on trees).
In programming terms, you can have a class called Apple, which has variables size:big, shape:round, habitat:grows on trees. To have 5 apples in your basket, you need to instantiate 5 apples. Apple apple1, Apple apple2, Apple apple3 etc....
Alternatively: Objects are the definitions of something, instances are the physical things.
Does this make sense?
Instance: instance means just creating a reference(copy).
object: means when memory location is associated with the object (is a run-time entity of the class) by using the new operator.
In simple words, Instance refers to the copy of the object at a particular time whereas object refers to the memory address of the class.
Object:
It is a generice term basically it is a Software bundle that has state(variables) and behaviour(methods)
Class:
A blue print(template) for an object
instance-it's a unique object thing for example you create a object two times what does that mean is yo have created two instances
Let me give an example
Class student()
{
private string firstName;
public student(string fname)
{
firstName=fname;
}
Public string GetFirstName()
{
return firstName;
}
}
Object example:
Student s1=new student("Martin");
Student s2=new student("Kumar");
The s1,s2 are having object of class Student
Instance:
s1 and s2 are instances of object student
the two are unique.
it can be called as reference also.
basically the s1 and s2 are variables that are assigned an object
Objects and instances are mostly same; but there is a very small difference.
If Car is a class, 3 Cars are 3 different objects. All of these objects are instances. So these 3 cars are objects from instances of the Car class.
But the word "instance" can mean "structure instance" also. But object is only for classes.
All of the objects are instances.
Not all of the instances must be objects. Instances may be "structure instances" or "objects".
I hope this makes the difference clear to you.
Let's say you're building some chairs.
The diagram that shows how to build a chair and put it together corresponds to a software class.
Let's say you build five chairs according to the pattern in that diagram. Likewise, you could construct five software objects according to the pattern in a class.
Each chair has a unique number burned into the bottom of the seat to identify each specific chair. Chair 3 is one instance of a chair pattern. Likewise, memory location 3 can contain one instance of a software pattern.
So, an instance (chair 3) is a single unique, specific manifestation of a chair pattern.
Quick and Simple Answer
Class : a specification, blueprint for an object...
Object : physical presence of the class in memory...
Instance : a unique copy of the object (same structure, different data)...
An object is a construct, something static that has certain features and traits, such as properties and methods, it can be anything (a string, a usercontrol, etc)
An instance is a unique copy of that object that you can use and do things with.
Imagine a product like a computer.
THE xw6400 workstation is an object
YOUR xw6400 workstation, (or YOUR WIFE's xw6400 workstation) is an instance of the xw6400 workstation object
Java is an object-oriented programming language (OOP). This means, that everything in Java, except of the primitive types is an object.
Now, Java objects are similar to real-world objects. For example we can create a car object in Java, which will have properties like current speed and color; and behavior like: accelerate and park.
That's Object.
Instance, on the other side, is a uniquely initialized copy of that object that looks like Car car = new Car().
Check it out to learn more about Java classes and object
Once you instantiate a class (using new), that instantiated thing becomes an object. An object is something that can adhere to encapsulation, polymorphism, abstraction principles of object oriented programming and the real thing a program interacts with to consume the instance members defined in class. Object contains instance members (non-static members).
Thus instance of a class is an object. The word ‘instance’ is used when you are referring to the origin from where it born, it's more clearer if you say ‘instance of a class’ compared to ‘object of a class’ (although the latter can be used to).
Can also read the 'Inner classes' section of this java document on nested classes - https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
I can't believe, except for one guy no one has used the code to explain this, let me give it a shot too!
// Design Class
class HumanClass {
var name:String
init(name:String) {
self.name = name
}
}
var humanClassObject1 = HumanClass(name: "Rehan")
Now the left side i.e: "humanClassObject1" is the object and the right side i.e: HumanClass(name: "Rehan") is the instance of this object.
var humanClassObject2 = HumanClass(name: "Ahmad") // again object on left and it's instance on the right.
So basically, instance contains the specific values for that object and objects contains the memory location (at run-time).
Remember the famous statement "object reference not set to an instance of an object", this means that non-initialised objects don't have any instance.
In some programming languages like swift the compiler will not allow you to even design a class that don't have any way to initialise all it's members (variable eg: name, age e.t.c), but in some language you are allowed to do this:
// Design Class
class HumanClass {
var name:String // See we don't have any way to initialise name property.
}
And the error will only be shown at run time when you try to do something like this:
var myClass = HumanClass()
print(myClass.name) // will give, object reference not set to an instance of the object.
This error indicates that, the specific values (for variables\property) is the "INSTANCE" as i tried to explain this above!
And the object i.e: "myClass" contains the memory location (at run-time).
This answer may be seen as trite, but worrying about the differences between an instance and object is already trite city.
I think its best depicted in javascript:
let obj= {"poo":1}
// "obj" is an object
verses
Class Trash {
constructor(){this.poo = 1;}
}
let i = new Trash();
// "i" is an instance
When a variable is declared of a custom type (class), only a reference is created, which is called an object. At this stage, no memory is allocated to this object. It acts just as a pointer (to the location where the object will be stored in future). This process is called 'Declaration'.
Employee e; // e is an object
On the other hand, when a variable of custom type is declared using the new operator, which allocates memory in heap to this object and returns the reference to the allocated memory. This object which is now termed as instance. This process is called 'Instantiation'.
Employee e = new Employee(); // e is an instance
However, in some languages such as Java, an object is equivalent to an instance, as evident from the line written in Oracle's documentation on Java:
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
An instance is a specific representation of an object. An object is a generic thing while an instance is a single object that has been created in memory. Usually an instance will have values assigned to it's properties that differentiates it from other instances of the type of object.
If we see the Definition of Object and Instance object -
Memory allocated for the member of class at run time is called object or object is the instance of Class.
Let us see the Definition of instance -
Memory allocated For Any at run time is called as instance variable.
Now understand the meaning of any run time memory allocation happen in C also through Malloc, Calloc, Realloc such:
struct p
{
}
p *t1
t1=(p) malloc(sizeof(p))
So here also we are allocating run time memory allocation but here we call as instance so t1 is instance here we can not say t1 as object so Every object is the instance of Class but every Instance is not Object.
Object - An instance of a class that has its own state and access to all of the behaviour defined by its class.
Instance - Reference to an memory area for that particular class.
Class : A class is a blue print.
Object : It is the copy of the class.
Instance : Its a variable which is used to hold memory address of the object.
A very basic analytical example
Class House --> Blueprint of the house. But you can't live in the blue print. You need a physical House which is the instance of the class to live in. i.e., actual address of the object is instance. Instances represent objects.
There are 3 things you need to understand : Class , Object and Instance.
Class : Class is the blueprint code from which you will create an Object(s)
Object : When memory is allocated to the data entity (created from blueprint class) , that data entity or reference to it is called Object
Instance : When data is filled in an Object , it becomes an instance of that Object. It can also be called a state of that Object.
Example : In context with C# (objects are reference type here)
Lets say we have a class like this (This is your blueprint code)
public class Animal
{
//some fields and methods
}
We create an object like this
Animal a = new Animal();
Animal b = a;
Animal c = a;
Animal d = b;
So here is the question : How many objects and instances are here ?
Answer : There is only 1 object but 4 instances.
Why ?
In first line (Animal a = new Animal();),we created an Object from class Animal with new Operator. That Object is somewhere on your RAM. And the reference to that Object is in "a".
We have 1 object and 1 instance at this time.
Now in next line, we assign b with a. Here Object is not copied but the reference of object from "a" is stored in "b" too. Thus , we have 2 instances , "a and b".
This goes on and we only copy reference of same object located at some memory.
Finally , we have 4 instances "a,b,c,d" of a single object that was created with new Operator.
(Read how reference type works in C# for more. I hope you understand my language)
each object said to be an instance of its class but each instance of the class has its own value for each attributes
intances shares the attribute name and operation with their intances of class but an object contains an implicit reference to his on class
I can't believe this could be hard to be explain but it actually easier than all the answers I read. It just simple like this.
Firstly, you need understand the definition:
Instance is a **unique copy-product of an Object.
**unique - have different characteristic but share the same class compare to object
Object is a name that been used to keep the Class information (i.e
method)
Let say, there is an toy_1 as an object.
There is also toy_2 as an object ----> which ALSO an INSTANCE to toy_1.
At the same time, toy_1 also an INSTANCE to toy_2. (remember again INSTANCE is a COPY-PRODUCT)
That is why most of the answer I found said it is INTERCHANGABLE. Thank you.
I think if we consider other approaches than OOP (mainly by assuming the term Class hasn't always been used, as it's the case for many C projects, which still applied the concept of Objects), following definitions would make the most sense:
A Class defines an interface that objects adhere to.
An Object is an aggregate of different fields. (It doesn't have to "physically" exist, but it can).
All Objects of the same Class can be used in the same way, defined by the Class.
An Instance is a unique realization of an Object.
As many OOP languages use static typing, the Object description is usually part of the Class already. As such, when talking about an Object in C/C++, what usually is meant is the Instance of an Object.
In languages that do not have static typing (such as JavaScript), Objects can have different fields, while still sharing the same Class.
Regarding the difference between an object and an instance, I do not think there is any consensus.
It looks to me like people change it pretty much interchangeably, in papers, blog posts, books or conversations.
As for me, the way I see it is, an object is a generic and alive entity in the memory, specified by the language it is used in. Just like the Object class in Java. We do not much care its type, or anything else associated with it, whether it is managed by a container or not.
An instance is an object but associated with a type, as in this method accepts Foo instances, or you can not put Animal instances in an instance of
a List of Vehicles.
objects for example have locks associated with them, not instances, whereas instances have methods. objects are garbage collected, not instances.
But as I said, this is only how I see it, and I do not think there is any organisation we can refer to for a standard definition between them and everyone will pretty much have their slightly different understanding / definitions (of course within limits).
An object is a generic thing, for example, take a linear function in maths
ax+b is an object, While 3x+2 is an instance of that object
Object<<< Instance
General<<< Specific
There is nothing more to this
An object can be a class, say you have a class called basketball.
but you want to have multiple basketballs so in your code you create more than 1 basketball
say basketball1 and basketball2.
Then you run your application.
You now have 2 instances of the object basketball.
Object refers to class and instance refers to an object.In other words instance is a copy of an object with particular values in it.

What is the difference between association, aggregation and composition?

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.

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.