Abstract Classes in C#
What is an Abstract Class?
An abstract class in C# is a class that cannot be instantiated directly. It is intended to be a base class for other classes. Abstract classes can contain abstract methods (without implementation) as well as concrete methods (with implementation).
Why Use Abstract Classes?
Abstract classes are used to provide a common base class for derived classes. They are useful when you want to enforce certain behaviors in derived classes while still allowing the base class to contain shared functionality.
Example of Abstract Class
Abstract classes can have both abstract and concrete methods. Abstract methods must be implemented by the derived classes.
Example of Abstract Class in C#:
public abstract class Animal
{
// Abstract method (does not have a body)
public abstract void MakeSound();
// Concrete method (has a body)
public void Sleep()
{
Console.WriteLine("Sleeping...");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark!");
}
}
// Usage
Dog dog = new Dog();
dog.MakeSound(); // Outputs: Bark!
dog.Sleep(); // Outputs: Sleeping...
In this example, the Animal
class is abstract and contains both an abstract method MakeSound
and a concrete method Sleep
. The Dog
class inherits from Animal
and provides the implementation for MakeSound
.
Key Characteristics of Abstract Classes
- An abstract class cannot be instantiated directly.
- It can contain both abstract methods (without implementation) and concrete methods (with implementation).
- Derived classes must implement all abstract methods in the abstract class.
- Abstract classes can have constructors, fields, properties, and methods like regular classes.
Abstract Class vs Interface
While both abstract classes and interfaces provide a way to define methods that must be implemented by derived classes, they have key differences:
- Abstract Class: Can have both abstract and concrete methods, and can contain fields, properties, and constructors.
- Interface: Cannot have fields or constructors. All members are abstract by default (prior to C# 8.0).
- Inheritance: A class can inherit from only one abstract class but can implement multiple interfaces.
Key Points to Remember
- Abstract classes are used to define common behavior that can be shared among related classes.
- Derived classes must implement all abstract methods of the abstract class.
- An abstract class can have fields, properties, and methods with implementation, unlike an interface.