Curriculum
In C#, an abstract class is a class that cannot be instantiated, meaning you cannot create an object of an abstract class directly. Instead, you can create objects of its derived classes, which must provide implementations for all the abstract members of the abstract class.
Here’s an example of an abstract class in C#:
public abstract class Animal { public abstract void MakeSound(); public void Sleep() { Console.WriteLine("The animal is sleeping"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow!"); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Woof!"); } }
In this example, we have an abstract class Animal
with an abstract method MakeSound()
and a non-abstract method Sleep()
. The Animal
class cannot be instantiated directly because it is abstract, but we can create objects of its derived classes Cat
and Dog
. These derived classes must provide implementations for the MakeSound()
method, otherwise they will also be marked as abstract.
Here are some rules to keep in mind when using abstract classes in C#:
sealed
, which means it cannot be further inherited by any other class.In summary, abstract classes in C# provide a way to define a base class with some members that do not have an implementation, and force derived classes to provide implementations for these members. This allows for a more flexible and extensible design of object-oriented programs.