Reputation: 137
Just begin to learn OOPs concepts and i am bit confused in relations, Aggregation and Composition I wanna know whether the following code is Composition or not
class Person {
String name;
Dob dob;
public Person(String name, int date, String month, int year) {
this.name = name;
dob = new Dob(date, month, year);
}
public String getName() {
return name;
}
public Dob getDob() {
return dob;
}
}
class Dob {
int date, year;
String month;
public Dob(int date, String month, int year) {
this.date = date;
this.year = year;
this.month = month;
}
@Override
public String toString() {
return date + " " + month + " " + year;
}
}
public class JavaApplication6 {
public static void main(String[] args) {
Person person = new Person("omar", 4, "march", 1996);
System.out.println(person.name + " " + person.dob);
}
}
if it is not Composition the how to achieve it by considering the same example Thanks you
Upvotes: 0
Views: 60
Reputation: 131346
Aggregation and Composition make me think to UML concepts : the first one is a strong relationship between an entity and another while the second one is a still stronger relationship between an entity and another.
For example the compositor deletion triggers the deletion of the composed entity in the composition relationship but not in the aggregation relationship.
In Java, only the notion of composition is commonly used and it doesn't mean the same thing.
It means that an object/class is composed of another one. It is a synonym of wrapper.
We often oppose it to inheritancy.
In your case, Person
doesn't inherit from Dob
but owns a field of Dob
. So it composes/wraps it.
The UML composition is not necessary easy to translate in terms of Java objects.
It is more natural as you work with an ORM where the notion of row deletion and on delete cascade
make sense.
For plain Java objects, the deletion/collect of the objects is performed by the garbage collector (GC).
So while the Dob
instance is referenced by another object, it will be alive.
To ensure its deletion you should probably make the Dob
field not accessible to any other object but the Person
instance that composes it.
To achieve it you could remove the getter in Person
that returns the Dob
instance.
In this way, as soon the Person
is eligible to be collected by the GC, it will also be the case for the Dob
instance that is only referenced by the Person
object.
Upvotes: 1