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.
class Move {
public void Roll() { ... }
}
class Player {
public void PerformAction(Move move) {
move.Roll();
}
}
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.
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());
}
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.
class Address{
//code here
}
class StudentClass{
private Address studentAddress;
//code here
}
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.
class Room {
//code here
}
class House {
private Room room;
//code here
}
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).
abstract class Vehicle {
//code here
}
class Car extends Vehicle {
//code here
}
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)
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.