← Foundations path
.NETFoundations 10 / 37

Composition: is-a vs has-a

“What is composition, and when do you use it instead of inheritance?”

Inheritance says a class **is a** kind of another. Composition says a class **has a** part and calls it. Use it when one part changes for a different reason than the rest.

See it

1/9Before. is the parent. and inherit from it: each is a contract.

In plain words

Inheritance is for a true family: a is a kind of , so it gets the contract's data and methods. Composition is for a part: a contract has a late-fee rule, keeps it in a field, and calls it when it needs a fee. You reach for composition when one part changes for a different reason than the rest, like late fees changing per lender (BMW FS, UDC). With inheritance only, every kind × every lender becomes its own class, and the count multiplies. With composition, you write each kind once and each rule once, and you plug the rule in through the .

Say it in the interview

In the lending API

The rule as an interface, two rules, the contract that holds one, and the code that builds it. Press Next line to walk through.

Lending.sln · where these 6 files sit
  • src/
    • Domain/
      • Fees/
    • Billing/
Diagram · step 5The fix: take the late fee out into its own small classes behind one interface, .
ILateFeeRule.cs · line 1 · 1 of 1The promise every rule keeps: give me days late, I give you a fee.

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

Read more: Wikipedia: composition over inheritance · Microsoft Learn: interfaces