Lesson 36 +10 XP

C# Abstraction

C# Abstraction

Abstraction means hiding the details and showing only the essential parts. In C# you do this with abstract classes and abstract methods.

Abstract classes and methods

  • An abstract class cannot be instantiated - you can't do new AbstractClass().
  • An abstract method has no body; it's declared and left for subclasses to implement.
abstract class Animal
{
  public abstract void animalSound();

  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

Inheriting an abstract class

A subclass must implement every abstract method:

class Pig : Animal
{
  public override void animalSound()
  {
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Pig myPig = new Pig();
    myPig.animalSound();   // The pig says: wee wee
    myPig.sleep();         // Zzz
  }
}

Why use abstraction?

  • Forces structure - every subclass must implement the abstract methods.
  • Hides complexity - callers see a simple interface, not implementation details.
  • The abstract class can also contain normal, shared methods (like sleep).

Abstract vs sealed

  • abstract - must be inherited.
  • sealed - cannot be inherited.

TL;DR

  • abstract classes cannot be instantiated.
  • abstract methods have no body and must be overridden.
  • Subclasses implement the abstract methods.
  • Abstraction hides complexity and enforces structure.