Class relationships: is-a, has-a, uses
The six lines in a class diagram and the C# each one becomes: inheritance, implementation, composition, aggregation, association, dependency.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Inheritance and implementation are "is a". Composition and aggregation are "has a", and differ in who owns the part's lifetime. Association is "knows about" through a field; dependency is "uses for a moment" through a parameter.
Code
public interface IPayment { bool Pay(decimal amount); }
public class CardPayment : IPayment { public bool Pay(decimal a) => true; }
public class Customer { }
public class VipCustomer : Customer { }
public class Product { public decimal Price; }
public class OrderLine { public Product Product; public int Qty; }
public class Order
{
readonly List<OrderLine> _lines = new(); // created here, dies with Order
public Customer Customer { get; } // passed in, lives on
public Order(Customer c) => Customer = c;
public bool Checkout(IPayment p) => p.Pay(0); // used, not stored
}Tips
- Composition: filled diamond on the owner. Aggregation: hollow diamond. If unsure, say it in words; interviewers care about the reasoning.
- Prefer composition over inheritance when you only want to reuse behaviour, not express a true is-a.
- A dashed line is weaker than a solid one: implementation is weaker than inheritance, dependency weaker than association.
In the .NET library
C# allows one base class but many interfaces, which is why designs lean on interfaces plus composition.