Abstraction is the concept of exposing only the essential details and hiding unnecessary information from the user. This helps in reducing complexity and increasing maintainability. The principle of abstraction can be implemented by using either abstract classes or interfaces (which will be the subject of in-depth discussion in the later tutorial).
Abstract Classes:
An abstract class in C# is a class that cannot be instantiated, meaning you cannot create an object of an abstract class (to access it, it must be inherited from another class). It's designed to act as a base class (parent class) for other classes. An abstract class can have data, and it can have complete or incomplete methods. Methods that are declared but not implemented in an abstract class are known as abstract methods. Abstract classes are created when you want to provide a common, generalized form of a concept that can be reused multiple times.
For instance, an Animal class can serve as an abstract class, with the understanding that all animals breathe, eat, and move, but each animal does so differently. Here's a simple example:
abstract class Animal
{
public abstract void Eat();
public abstract void Move();
public void Breathe()
{
Console.WriteLine("Breathing...");
}
}
In this example, Animal is an abstract class with two abstract methods Eat and Move, and one non-abstract method Breathe.
Abstract Methods:
Abstract methods are declared in an abstract class, and they don't have any implementation in the abstract class itself. They are meant to be overridden in the derived classes.
Here's an example of a Dog class that inherits from Animal and implements the abstract methods:
class Dog : Animal
{
public override void Eat()
{
Console.WriteLine("The dog eats.");
}
public override void Move()
{
Console.WriteLine("The dog moves.");
}
}
The Dog class is a concrete class (i.e., it is not abstract) and therefore it must provide an implementation for the Eat and Move methods.
NOTE: Derived classes that inherit from the abstract class are responsible for providing an implementation for these abstract methods. If a derived class does not provide implementations for all of the abstract class's abstract methods, then the derived class must also be declared as abstract.(alert-success)