Reputation: 1662
I want to know how to identify composition and aggregation code in java. I have C++ Code, But I don't understand how to write in java.
Composition
class A {};
class B { A composited_A; };
Aggregation via Pointer
class A {};
class B
{
A* pointer_to_A;
B(A anA){
pointer_to_A = &anA;
}
Can anyone please tell me how both are working in JAVA. (I know what is meant by Composition and aggregation ) };
Upvotes: 5
Views: 3457
Reputation: 1662
I think this is best way to express Composition and Aggregation With Java Code.
Composition
public class Person
{
private final Name name;
public Person (String fName, String lName)
{
name = new Name(fName, lName);
}
//...
}
Aggregation
public class Person
{
private Costume currentClothes;
public void setClothes(Costume clothes)
{
currentClothes = clothes;
}
//...
}
Upvotes: -1
Reputation: 546123
Java itself simply does not make the distinction between composition and aggregation. You cannot express the idea of ownership of a reference in the Java type system – if you explicitly need to express ownership you must denote this with some other means (usually simply by constructing a new object to be stored in the instance of a class).
Since Java has a GC, ownership for memory doesn’t need to be expressed at all; memory is owned and managed solely by the GC. Of course, the same is not true for other resources and here you might still want to express ownership.
Upvotes: 8
Reputation: 16364
In Java, objects are only referenced by pointers. This means that a field of type A
is really a reference to an A
object. It also means that that field will always start as a null pointer, and you must explicitly assign it to new A()
or whatever.
Edit:
class B {
A a;
B(A a) {
this.a = a;
}
B() {
this(new A());
}
}
Upvotes: 1