educative.io

One way and two way association

how come the classes you have mentioned have one way and two way association?

Hi @Geet_Aggarwal !!
In a class diagram, associations represent relationships between classes. These associations can be one-way or two-way, depending on whether the relationship is navigable in one direction or both directions between the connected classes.

  1. One-way association(Unidirectional association):
    In a one-way association, the relationship is navigable from one class to another but not vice versa. It means that one class knows about the other class, but the other class does not necessarily know about the first class.

    Example of one-way association:

    ClassA -----> ClassB
    

    In this example, ClassA is associated with ClassB, but ClassB doesn’t have a direct association back to ClassA.

  2. Two-way association(Bidirectional association):
    In a two-way association, the relationship is navigable in both directions between the connected classes. It means that both classes know about each other and have a direct connection.

    Example of two-way association:

    ClassA <----> ClassB
    

    In this example, ClassA is associated with ClassB, and ClassB is also associated with ClassA. Both classes can access each other through this association.

To further illustrate, let’s consider a real-world example:

Imagine you have two classes: Person and Address.

  • One-way association:
    A Person class can have an attribute representing their home Address. The Person class knows about the Address class (one-way association) to store the address information, but the Address class doesn’t necessarily know which person it belongs to.

  • Two-way association:
    In a two-way association, the Employee class has an attribute called company , which stores the reference to the Company the employee belongs to. Conversely, the Company class maintains a list of employees associated with it through an attribute called employees . This allows bidirectional navigation, as each Employee knows its Company , and each Company knows its list of employees.
    I hope it helps. Happy Learning :blush: