In object-oriented programming (OOP), relationships between classes describe how different classes interact or are connected to each other.
Think of classes like people in a family or team — they can be related in different ways (parent-child, friend, colleague, etc.).
A) Association
Definition: A general connection between two classes where one knows about the other.
Example: A Customer
places an Order
.
Notes: Can be one-to-one, one-to-many, or many-to-many.
public class Customer
{
public string Name { get; set; }
public Order Order { get; set; } // Association
}
public class Order
{
public int OrderId { get; set; }
}
B) Aggregation (Has-A)
Definition: A special type of association where one class contains another, but the contained object can exist independently.
Example: A Team
has Players
, but a Player
can exist without a Team
.
public class Team
{
public List<Player> Players { get; set; } // Aggregation
}
public class Player
{
public string Name { get; set; }
}
C) Composition (Strong Has-A)
Definition: A stronger form of aggregation where the contained object cannot exist without the container.
Example: A House
has Rooms
— if the House
is destroyed, the Rooms
are gone too.
public class House
{
public List<Room> Rooms { get; set; } = new List<Room>(); // Composition
}
public class Room
{
public string Name { get; set; }
}
D) Inheritance (Is-A)
Definition: A relationship where one class is a specialized version of another.
Example: Car
is a Vehicle
.
public class Vehicle
{
public int Speed { get; set; }
}
public class Car : Vehicle
{
public string Brand { get; set; }
}
E) Dependency (Uses-A)
Definition: A temporary relationship where one class uses another class to perform a task.
Example: A ReportService
uses a PdfGenerator
.
public class ReportService
{
public void GenerateReport(PdfGenerator generator) // Dependency
{
generator.Create();
}
}
public class PdfGenerator
{
public void Create() { }
}
Summary Table
Relationship | Example (English) | Lifespan Link? | Strong/Weak? |
---|---|---|---|
Association | Customer ↔ Order | No | Weak |
Aggregation | Team → Player | No | Weak |
Composition | House → Room | Yes | Strong |
Inheritance | Car → Vehicle | N/A | Strong |
Dependency | Service → Logger | No | Weak |
Leave a Reply