Showing posts with label Abstract Class. Show all posts
Showing posts with label Abstract Class. Show all posts

Sunday, 30 November 2025

Can an Abstract Class Have a Constructor?

Can an Abstract Class Have a Constructor?

Yes — an abstract class can have a constructor in C#.

Why an Abstract Class Constructor is Allowed in C#

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

C# Code Example: Abstract Class Constructor with base()

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.

Abstract Class vs Interface

In C#, both abstract classes and interfaces handle abstraction differently: abstract classes share base code and state among related types, while interfaces define a contract of capabilities across unrelated types.

What Are Abstract Classes and Interfaces?

  • Abstract class: An uninstantiable class (using abstract) supporting both abstract and concrete members.
  • Interface: A contract (using interface) dictating required members without dictating internal implementation.

Abstract Class vs Interface: Key Differences

Aspect Abstract Class Interface
Members & State Abstract and concrete methods/properties; can hold instance or static fields. Signatures only (though C# 8+ allows default implementations); no instance fields.
Modifiers & Setup Supports standard access modifiers; can define constructors. Members are implicitly public; cannot have constructors.
Inheritance Single class inheritance only. Multiple interface implementation supported.
Use Case "Is-a" relationship for shared base logic. "Can-do" relationship for cross-cutting capabilities.

When to Use Abstract Class vs Interface

  • Abstract class: Best for closely related classes sharing base behavior or state to eliminate duplicate code.
  • Interface: Best for defining flexible contracts across disparate, unrelated types.

C# Code Example: Using Both Together

abstract class Animal
{
    public string Name;
    public abstract void MakeSound();
    public void Sleep() { Console.WriteLine("Sleeping..."); }
}

interface IWalker
{
    void Walk();
}

class Dog : Animal, IWalker
{
    public override void MakeSound() { Console.WriteLine("Bark!"); }
    public void Walk() { Console.WriteLine("Dog is walking..."); }
}

How This Example Works

  • Animal provides shared state and concrete logic (Sleep()).
  • IWalker enforces the walking contract.
  • Dog combines both through single class inheritance and interface implementation.

What is an abstract class?

An abstract class in C# serves as an uninstantiable base class containing both abstract members (without implementation) and concrete members (with implementation) for derived classes to inherit.

Key Features of Abstract Classes in C#

  • No Direct Instantiation: Prevents creating objects directly via new.
  • Abstract & Concrete Members: Supports abstract declarations alongside standard implemented methods.
  • Enforces Base Structure: Guarantees derived classes implement all required abstract members.

Important Rules to Remember

  • Use the override Keyword: Derived non-abstract classes must use override to implement inherited abstract methods.
  • Can Have Constructors: Abstract classes can define constructors to initialize shared fields (see Can an Abstract Class Have a Constructor?).
  • Single Inheritance Only: A C# class can inherit from only one abstract class at a time.

C# Abstract Class Code Example

abstract class Animal
{
    public abstract void MakeSound(); // abstract method (no body)

    public void Sleep()               // concrete method (with body)
    {
        Console.WriteLine("Sleeping...");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark!");
    }
}

In this example, Animal is an abstract class. You cannot create new Animal(), but you can instantiate Dog, which inherits Sleep() and implements MakeSound().