The heart of object-oriented design is establishing relationships among the classes. Classes interact and relate to one another in various ways.
The simplest interaction is when a method in one class is used to call a method in a second class. For example, the Manager
class might have a method that calls the UpdateSalary
method on an object of type Employee
. We then say that the Manager
class and the Employee
class are associated. Association among classes simply means they interact.
Some complicated types are composed of other types. For example, an automobile might be composed of wheels, engine, transmission, and so forth. You might model this by creating a Wheel
class, an Engine
class, and a Transmission
class. You could then create an Automobile
class, and each automobile object would have four instances of the Wheel
class and one instance each of the Engine
and Transmission
classes. This is commonly called the has-a relationship. Another way to view this relationship is to say that the Automobile
class aggregates the Wheel
, Engine
, and Transmission
classes, or that the Automobile
class is composed of Wheel
, Engine
, and Transmission
objects.
Some programming languages (such as C++) distinguish between the is-composed-of (composition) and the has-a (aggregation) relationships, but this distinction does not apply in C#, and they are treated as equivalent.
This process of aggregation (or composition) allows you to build very complex classes by assembling and combining relatively simple classes. The .NET Framework provides a String
class to handle text strings. You might create your own Address
class out of five text strings (address line 1, address line 2, city, state, and zip code). You might then create a second class, Employee
, which has as one of its members an instance of Address
.