How to write composition and aggregation in java

I want to know how to determine the composition and aggregation code in java. I have C ++ code, but I don't understand how to write in java.

Structure

class A {};
class B { A composited_A; };

Pointer Aggregation

class A {};
class B
{
A* pointer_to_A;
B(A anA){ 
pointer_to_A = &anA;
}

Can someone tell me how both work in JAVA. (I know what is meant by composition and aggregation)};

+5
source share
3 answers

Java itself simply does not distinguish between composition and aggregation. You cannot express the idea of ​​owning a link in a system such as Java — if you explicitly need to express ownership, you must indicate this using some other means (usually just by creating a new object that will be stored in an instance of the class).

Java GC, ; GC. , , .

+8

Java . , A A. , , new A() - .

Edit:

class B {
   A a;

   B(A a) {
      this.a = a;
   }

   B() {
      this(new A());
   }
}
+1

, Java.

public class Person  
{  
    private final Name name;  

    public Person (String fName, String lName)  
    {  
        name = new Name(fName, lName);  
    }  

    //...  
}  

public class Person  
{  
    private Costume currentClothes;  

    public void setClothes(Costume clothes)  
    {  
        currentClothes = clothes;  
    }  

    //...  
}  

-1

All Articles