C# Intermediate: OOP, Interfaces & Events

Lesson 2 of 7

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 interface declares 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 class can mix fully-implemented members (Heal) with abstract members 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

InterfaceAbstract class
Shared implementation?NoYes
Multiple per class?YesNo, only one base class
Use for"can do" contracts"is a" shared foundation

📝 Interfaces & Abstract Classes Quiz

Passing score: 70%
  1. 1.How many interfaces can a single class implement?

  2. 2.You cannot create an instance of an ____ class directly, only of a concrete subclass.

  3. 3.An interface can declare instance fields (variables) directly.