Abstract classes

An abstract class in C# is a class that cannot be instantiated, that is, the program execution cannot create an object of this class. Instead, these classes can only act as base classes from which other classes can inherit. 

We use the abstract class in scenarios where we specifically want all the deriving classes to implement the specific implementation of a particular function that's declared in the base class. The following are some of the properties of an abstract class:

  • Just like all the other classes, an abstract class can have both functions and properties.
  • An abstract class can have both abstract and non-abstract functions.

Let's take a look at a program to analyze how abstract classes work. We will define an Animal class using the abstract keyword. Now, let's assume that each animal type, such as dog, speaks differently, so they must implement the function in their own way. To implement this, we will declare our base Animal class as abstract and have an abstract method Speak in it. Review that if we try to implement the Speak method, the compiler throws an error:

To remove this error, we can simply remove the declaration of the abstract method:

public abstract class Animal
{
public abstract void Speak();
public void Walk()
{
Console.WriteLine("Base Animal Walk Functionality");
}
}

Now, let's create a Dog class that inherits from this base class of Animal. Note that the compiler will throw an error if the Speak method is not implemented:

We can get over this error by creating an implementation of the Speak function:

public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("A dog will bark");
}
}

Please note that we use the override keyword to let the compiler know that we are overriding the implementation of the abstract function called Speak in the derived class.

In the next section, we will look at the same example and understand how abstract methods differ from virtual methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.82.154