Sunday, 30 November 2025

Can an Abstract Class Have a Constructor?

Can an Abstract Class Have a Constructor?

Can an Abstract Class Have a Constructor?

Yes — an abstract class can have a constructor in C#. :contentReference[oaicite:0]{index=0}

Why it’s allowed (and useful)

  • Even though you can’t instantiate the abstract class itself, constructors in it are called when a concrete subclass is instantiated. :contentReference[oaicite:1]{index=1}
  • That constructor allows initialization of fields or shared setup logic common to all subclasses. :contentReference[oaicite:2]{index=2}
  • In C#, such constructors are often marked protected (or internal/protected internal), so they can only be used by subclasses — not from outside. :contentReference[oaicite:3]{index=3}

Example in C# + HTML-style illustration

abstract class Shape
{
    public string Color { get; }

    // Constructor of the abstract class
    protected Shape(string color)
    {
        Color = color;
        Console.WriteLine($"Shape created with color {color}");
    }

    public abstract double CalculateArea();
}

class Square : Shape
{
    public double Side { get; }

    public Square(string color, double side) : base(color)
    {
        Side = side;
    }

    public override double CalculateArea()
    {
        return Side * Side;
    }
}

class Program
{
    static void Main()
    {
        Square square = new Square("red", 5);
        Console.WriteLine($"Area of square: {square.CalculateArea()}");
    }
}
    

In this example, Shape is declared abstract and defines a constructor that initializes a Color property. The derived class Square calls that constructor using : base(color). When new Square(...) is executed, Shape’s constructor runs first (to initialize shared data), then Square’s constructor completes.

No comments:

Post a Comment