Interfaces and Abstract Classes
Two ways to define a contract that other classes must implement, with different tradeoffs.
interface IDamageable
{
void TakeDamage(int amount);
}
abstract class Character
{
public int Health = 100;
public abstract void Attack(); // no body, must be implemented
public void Heal(int amount) => Health += amount; // shared behavior
}
class Player : Character, IDamageable
{
public override void Attack() => Console.WriteLine("Player attacks!");
public void TakeDamage(int amount) => Health -= amount;
}
Interfaces
- An
interfacedeclares members with no implementation, any class or struct that implements it must provide one. - A class can implement multiple interfaces (C# only allows single inheritance from a base class, but unlimited interfaces).
- Interfaces describe what a type can do (
IDamageable,IComparable), regardless of what it is.
Abstract classes
- An
abstract classcan mix fully-implemented members (Heal) withabstractmembers that force derived classes to implement them (Attack). - You cannot create an instance of an abstract class directly (
new Character()is an error), only of a concrete subclass. - A class can inherit from only one base class (abstract or not), but implement any number of interfaces.
When to use which
| Interface | Abstract class | |
|---|---|---|
| Shared implementation? | No | Yes |
| Multiple per class? | Yes | No, only one base class |
| Use for | "can do" contracts | "is a" shared foundation |