DEV Community

Tommy
Tommy

Posted on

Common types of OOP relationships and their UML representation

Code reuse is one of the many benefits of OOP (object-oriented programming). Reusability is feasible because of the various types of relationships that can be implemented among classes. This article will demonstrate the types of relationships (from weak to strong) using Java code samples and the symbols in the UML (unified modeling language) class diagram.

Dependency

Is a relationship when objects of a class work briefly with objects of another class. Normally, multiplicity doesn’t make sense on a dependency.

Dependency UML Symbol

class Move { 
   public void Roll() { ... } 
}

class Player {
   public void PerformAction(Move move) { 
      move.Roll();
   }
}
Enter fullscreen mode Exit fullscreen mode

Association

This relationship transpires when objects of one class know the objects of another class. The relationship can be one to one, one to many, many to one, or many to many. Moreover, objects can be created or deleted independently.

Association UML Symbol

public static void main (String[] args) {
   Doctor doctorObj = new Doctor("Rick");
   Patient patientObj = new Patient("Morty");
   System.out.println(patientObj.getPatientName() +
        " is a patient of " + doctorObj.getDoctorName());
}
Enter fullscreen mode Exit fullscreen mode

Aggregation

Is a "has-a" type relationship and is a one-way form of association. This relationship exists when a class owns but shares a reference to objects of another class.

Aggregation UML Symbol

class Address{
//code here
}

class StudentClass{
   private Address studentAddress;
//code here
}
Enter fullscreen mode Exit fullscreen mode

Composition

Is a "part-of" type of relationship, and is a strong type of association. In other words, composition happens when a class owns & contains objects of another class.

Composition UML Symbol

class Room {
//code here
}

class House {
   private Room room;
//code here
}
Enter fullscreen mode Exit fullscreen mode

Inheritance

Is an "is-a" type of relationship. It's a mechanism that permits a class to acquire the properties and behavior of an existing class (or sometimes more classes, if the language allows multiple inheritance).

Inheritance UML Symbol

abstract class Vehicle {
//code here
}

class Car extends Vehicle {
//code here
}
Enter fullscreen mode Exit fullscreen mode

Note: When reading a UML class diagram, there is no starting point. It’s up to you to choose where to start. Simply follow the relationships, and then you can begin to understand and analyze the properties, behavior, and relations of the classes.

Top comments (1)

Collapse
 
rolivencia profile image
Ramiro Olivencia

Nice article Tommy. I'd suggest to change the example of the aggregation case for a more explicit one, since it may mislead and not be different enough in comparison to the composition case.