Summary
Abstraction is a goal; the abstract keyword is one C# tool for reaching it. Choose an ordinary, virtual or abstract method by whether derived classes keep, may change or must write it.
Journeyman · C# · OOP · Updated
After this lesson you can
- Choose an ordinary, virtual or abstract method for a base class member, by whether derived classes keep it, may change it or must write it
Key takeaways
- Abstraction is a goal; an
abstractclass is one C# tool for reaching it. - Make a member ordinary when every kind does it the same way,
virtualwhen a few kinds differ, andabstractwhen every kind does it differently. - Ask "could I sensibly create one of these?" If not, make the class abstract:
Characterstays concrete,BankAccountis abstract.
Abstraction means using an object through only what matters, and hiding the rest. Base classes are one way to get there: the more general a class, the more abstract it is. When a class is so general that an object of just that class makes no sense, mark it abstract: C# then won't let anyone create one, and makes every specific kind finish it.
So abstraction is an idea, a goal for code that's easy to use and to change. An abstract class is one C# tool for reaching it. (The next topic brings a second tool: interfaces.)
Three kinds of base class member
A base class decides, member by member, how much freedom its derived classes get:
| The member is | Derived classes | Use it when | Example |
|---|---|---|---|
| Ordinary | Keep it as it is | Every kind does it the same way | Deposit adds to the balance, for any account. |
virtual |
May override it | Most kinds share one way, a few differ | LevelUp is the same for most characters; an archer adds an arrow. |
abstract |
Must override it | Every kind does it differently, with no sensible default | Withdraw has a different rule for each kind of account. |
Abstract class or concrete base class?
Ask: could I sensibly create one of these?
new Character("Villager"): yes, a villager is a fine character.Characterstays concrete.new BankAccount("1001", 50m): no, the bank would ask "What kind?".BankAccountis abstract.new Shape(): no, a shape with no kind has no area.Shapeis abstract, with an abstractArea().
Check yourself
1 question to try on the lesson page.
So what
Every base class member is a choice: keep it, may change it, must write it. Make that choice on purpose, and the compiler will hold every derived class to it.