Inheritance: reuse with `base`
A derived class gets the base's members, extends them, and must keep the base's promises.
One class built on another
Inheritance declares that one class is a kind of another:
class Account
{
public decimal Balance { get; protected set; }
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentException("non-positive deposit");
Balance += amount;
}
}
class SavingsAccount : Account
{
public void AddMonthlyInterest(decimal rate)
{
Balance += Balance * rate; // reuses the inherited Balance
}
}
SavingsAccount carries everything Account has โ Deposit with its validation included โ and adds its own behavior. Callers holding a SavingsAccount can Deposit without knowing the derived type exists.
Extension, replacement, and base
A derived class can add members, or replace a non-virtual member with new (hiding) โ but replacing is a smell for beginners: the hidden base method still runs when called through a base reference.
The honest tool for "same idea, better implementation" is the constructor chain:
class SavingsAccount : Account
{
public SavingsAccount(string owner, decimal opening) : base(owner, opening) { }
}
base(...) forwards construction to the base constructor โ the base's invariants run first, always. base.Member also reaches the base's implementation from inside an override.