0

I Was going through the theories of these three concepts and it says : All three are has-a relationship and aggregation and composition are type of association:

  • In association there is no owner

  • In other two there is single owner.

  • In aggregation the child can exist independently. If the owner is deleted the child is not deleted. If you delete owner then child will still exist and can be assigned to other object as child.

I implemented this like this :

public class Aggregation {
    public static void main(String[] args) {

        HardDisk hardDisk = new HardDisk();
        Laptop laptop1 = new Laptop(hardDisk);
        System.out.println(laptop1);
        System.out.println(laptop1.hardDisk);
        laptop1 = null;
        System.gc();
        Laptop laptop2 = new Laptop(hardDisk);
        System.out.println(laptop2);
        System.out.println(laptop2.hardDisk);

    }
}

class HardDisk {
}

class Laptop {
    public HardDisk hardDisk;

    public Laptop(HardDisk hardDisk) {
        this.hardDisk = hardDisk;
    }
}
  • In composition the child is created with parent and deleted with parent. So owner and child relation is one to one here.

I implemented it like this :

public class Composition {
    public static void main(String[] args) {
        House house = new House();

    }
}
class House {
    private final Kitchen kitchen = new Kitchen();
    public Kitchen getKitchen() {
        return kitchen;
    }
}

class Kitchen {
}

Is that understanding correct or I am missing out something. Also I did it for aggregation and composition. What about association where we don't have any owner. How that should be done ? Also If class A has reference of B and B has reference of A then what type of association it will be?

New Bee
  • 1,007
  • 4
  • 18
  • 34

0 Answers0