Language: EN

csharp-clases-abstractas

What are abstract classes and how to use them in C#

An abstract class is a class that cannot be instantiated by itself and is mainly used as a base for other classes.

It contains one or more abstract methods, which are method declarations without implementation, forcing derived classes to provide their own implementation.

Additionally, they can contain concrete methods (methods with implementation), properties, and fields

Basic Syntax of an Abstract Class

The declaration of an abstract class is done using the abstract keyword. Let’s see it with an example,

public abstract class MyClass
{
    public abstract void MyAbstractMethod(); // Abstract method

    public void MyConcreteMethod() // Concrete method
    {
        Console.WriteLine("Hello from LuisLlamas.es");
    }
}

Implementing Abstract Classes

Let’s see how we can use abstract classes in C#. Suppose we are designing a system to manage different types of animals.

Creating Derived Classes

Now, we will create some classes that inherit from the abstract class Animal:

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The dog barks.");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The cat meows.");
    }
}

Here, we have created two classes, Dog and Cat, which inherit from Animal and provide their own implementation of the MakeSound method.

Using the Derived Classes

We can use these derived classes as follows:

Animal myDog = new Dog();
myDog.MakeSound(); // Output: The dog barks.
myDog.Sleep();     // Output: The animal is sleeping.

Animal myCat = new Cat();
myCat.MakeSound(); // Output: The cat meows.
myCat.Sleep();     // Output: The animal is sleeping.

In this example, we use references of type Animal to create instances of Dog and Cat. This allows the code to be more flexible and scalable, as we can add more types of animals in the future without changing the existing logic.