Explain with example.
🔑 Abstract Class
A class that cannot be instantiated directly.
Can contain:
Abstract members (methods/properties without implementation).
Concrete members (methods/properties with implementation).
Fields (state/data).
Constructors (to help derived classes initialize).
Supports inheritance → a class can inherit from only one abstract (or normal) class (C# is single inheritance).
Best used when you want to provide a base class with shared code/behavior and enforce certain contracts.
Example:
public abstract class Animal
{
public string Name { get; set; }
public abstract void MakeSound(); // Must be implemented in subclasses
public void Sleep() // Shared implementation
{
Console.WriteLine($"{Name} is sleeping...");
}
}
public class Dog : Animal
{
public override void MakeSound() => Console.WriteLine("Woof!");
}
A contract: defines what members a class must implement, but provides no implementation (until C# 8.0 where default interface methods became possible).
Cannot contain fields or constructors.
A class can implement multiple interfaces (supports multiple inheritance of contracts).
Best used to define capabilities or behaviors that can be applied across unrelated classes.
Example:
public interface IFlyable
{
void Fly();
}
public interface ISwimmable
{
void Swim();
}
public class Duck : IFlyable, ISwimmable
{
public void Fly() => Console.WriteLine("Duck is flying!");
public void Swim() => Console.WriteLine("Duck is swimming!");
}
Abstract Class:
When you have a strong is-a relationship (e.g., Dog is an Animal).
When you want to share base logic/fields among derived classes.
When future changes to the contract should apply to all subclasses.
Interface:
When you want to define a capability/behavior (e.g., "can fly", "can swim").
When unrelated classes should share the same contract (e.g., both Duck
and Airplane
implement IFlyable
).
When you need multiple inheritance of behavior contracts.
👉 Quick analogy:
Abstract class = a partially built house blueprint (with some walls already built, others just outlined).
Interface = a checklist of requirements (you must have walls, doors, and windows, but no details on how to build them)