Abstract Classes in C#
Introduction
Abstract classes are a fundamental concept in object-oriented programming (OOP). They are classes that cannot be instantiated on their own and are designed to be subclassed. Abstract classes often include abstract methods, which are methods without an implementation that must be overridden in derived classes.
Defining an Abstract Class
In C#, you define an abstract class using the abstract keyword. Here's a simple example:
public abstract class Animal {
public abstract void MakeSound();
public void Sleep() {
Console.WriteLine("Sleeping...");
}
}
In this example, Animal
is an abstract class with one abstract method MakeSound()
and one concrete method Sleep()
.
Implementing an Abstract Class
To use an abstract class, you must create a subclass that provides implementations for the abstract methods. Here’s how you can do that:
public class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Bark");
}
}
In this example, the Dog
class inherits from the Animal
abstract class and provides an implementation for the MakeSound()
method.
Using the Subclass
Once you've implemented the abstract methods, you can create instances of the subclass and use them in your code:
public class Program {
public static void Main() {
Animal myDog = new Dog();
myDog.MakeSound(); // Output: Bark
myDog.Sleep(); // Output: Sleeping...
}
}
Output:
Bark
Sleeping...
Abstract Properties
Abstract classes can also have abstract properties that must be overridden in derived classes:
public abstract class Shape {
public abstract double Area { get; }
}
public class Circle : Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public override double Area {
get {
return Math.PI * radius * radius;
}
}
}
In this example, the Shape
abstract class has an abstract property Area
, which is overridden in the Circle
class.
Why Use Abstract Classes?
Abstract classes are useful for defining a common base class that other classes can inherit from. They allow you to define methods and properties that must be implemented in derived classes, ensuring a consistent interface. This is particularly useful in large systems with complex hierarchies.
Abstract Classes vs Interfaces
While both abstract classes and interfaces can be used to define a contract for other classes to implement, they have some differences:
- Abstract classes can have implementations for some methods, while interfaces cannot.
- A class can inherit from only one abstract class but can implement multiple interfaces.
- Abstract classes can have fields and constructors, while interfaces cannot.
Conclusion
Abstract classes are a powerful feature in C# that allow you to define a base class with abstract methods and properties that must be implemented by derived classes. They provide a way to enforce a contract and ensure consistency across different parts of your application.