Abstract Classes
Abstract Classes
Section titled βAbstract ClassesβWhat it means
Section titled βWhat it meansβAn abstract class is a class that canβt be instantiated directly β it exists to be inherited from. It can mix fully-implemented methods (shared logic every subclass gets for free) with abstract methods, which have no body and must be overridden by any non-abstract derived class. Use it when subclasses share real, common implementation, not just a shared contract (thatβs what an interface is for).
Examples
Section titled βExamplesβpublic abstract class Shape{ public abstract double GetArea(); // no implementation -- subclasses must provide one
public void Describe() // shared implementation, inherited as-is { Console.WriteLine($"This shape has an area of {GetArea():F2}"); }}
public class Circle : Shape{ private readonly double _radius; public Circle(double radius) => _radius = radius;
public override double GetArea() => Math.PI * _radius * _radius;}
// var shape = new Shape(); // Error: cannot create an instance of an abstract classvar circle = new Circle(5);circle.Describe(); // "This shape has an area of 78.54"Common mistake
Section titled βCommon mistakeβForgetting override on the derived classβs implementation of an abstract member β without it, the compiler reports an error demanding you implement the abstract member, since a plain method with the same name doesnβt count as fulfilling the contract.
public abstract class Shape{ public abstract double GetArea();}
public class Circle : Shape{ public double GetArea() => Math.PI * 25; // Error: Circle does not implement Shape.GetArea()}
// Fix: add `override`public class Circle : Shape{ public override double GetArea() => Math.PI * 25;}Quick practice
Section titled βQuick practiceβ-
Can you create an instance of an abstract class directly with
new?Answer
No β abstract classes can't be instantiated; only their concrete (non-abstract) subclasses can. -
When should you use an abstract class instead of an interface?
Answer
When subclasses need to share real implementation, not just a method signature β abstract classes can hold shared logic and state; interfaces (until default interface methods) traditionally only define contracts. -
What must every non-abstract class that inherits from an abstract class do?
Answer
Provide anoverrideimplementation for every abstract member it inherits, or the class itself must also be declared abstract.