Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Composition and Aggregation in java

Tags:

java

c++

oop

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 ) };

like image 351
KKK Avatar asked Mar 25 '12 17:03

KKK


1 Answers

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.

like image 71
Konrad Rudolph Avatar answered Sep 20 '22 23:09

Konrad Rudolph