C# Intro to the Abstract classes
Tags: beginners, interface, unity3d, csharp
Published: 2019-07-17 08:50:50

---
title:C# Intro to the Abstract classes
published: true
description: 
tags: beginner, Interface, Unity,CSharp
---



##What are Abstract classes? 


###Abstract classes are a combination of both a normal class (default class) and an Interface.

<p><b>Abstract class as an Interface:</b>  Like an interface you're not allowed to have an instance of an abstract class anywhere and also you're allowed to create <I>"declaration only"</I> methods like the methods inside interfaces and can later demand the inheritor of the abstract class to write the definitions. 
<br>
<br>
<b>Abstract class as a normal class:</b> Like normal classes, you're allowed to have member variables, methods with definition and all the other advantages which will be covered in this post.
</p>

###Let's jump into an example to see how to create an abstract class. 
<p>
Let's write a scenario where we put a human to sleep at night. We can easily pull this off by creating a function <b>Sleep</b> in a separate class, Writing a functionality in a separate class enables the class to be independent and most importantly it will be really easier to be used in more than a single recipient class. 
<br>
So, we create the <b>Sleep</b> as an <b>abstract</b> class.(<I> There is a reason behind using an abstract class instead of a normal class. We will explain that in a bit but before that let's just see how to create an abstract class first.</I>)
</p>
<br>

<p>
<b>Creating an abstract class</b>
<br>
<br>
To make a class into an <b>"abstract"</b> class just put an <b><i>abstract</i></b> keyword right in front of the class keyword.
</p>
```c#
    public abstract class Sleep: MonoBehaviour
    {
      public bool sleep;
        public void GetSleep()
        {
          //the inherited organisms will sleep whence this method is called
          sleep = true;
        }

    }
```

<p>
 The <b>Sleep</b> abstract class has a method named <b>GetSleep()</b> which switches the <b>sleep</b> boolean to <b>true</b>. Upon making the sleep to <b>true</b> it will put the instance of a class which inherits the <b>Sleep</b> class to sleep.(<I>we will expand on the "the inherited organism will sleep" comment that has been written inside the sleep method after writing the rest of the structure required for a human to sleep</I>).
</p>
<br>
<br>
###Let's start writing the class that inherits the <b>Sleep</b> class. 
<br>
<p>
As planned this inheriting class will be the class <b>Human</b>. Since we've already wrote the functionality for the <b>sleep</b> inside the <b>Sleep</b> class. Thus we will pretty much leave the whole human class empty and inherit the sleep functionality from the <b>Sleep</b> abstract class. One of the main reasons to inherit this behavior instead of just writing this as part of the <b>Human</b> class is that the <b>Human</b> class does not have to know what sleep is.
</p>

###This is one of the main reasons an abstract class is called an abstract class.
<p> 
The inherited class doesn't need to know the structure of the class that is inside the class that it inherits. It is just like an actual human, A human like you who wishes to sleep. You close your eyes and expect yourself to be put to sleep, but you as a conscious self have no control over the process of sleep, there is no <b>"sleep"</b> button in your head that puts you to sleep. For you, the entire concept of sleep is <b><I>abstract<I></b>. You know how sleep can be triggered but cannot directly put yourself to sleep.
<br>
 The best thing you can do is to close your eyes and wait till your brain puts you to sleep. So like a human who doesn't need to know the internal structure of sleep, this <b>Human</b> class doesn't need to know the internal structure of a <b>Sleep</b> class and how it does the <b>sleep process</b>. For the <b>Human</b> class the internal structure of a <b>Sleep</b> class is <b>abstract</b>.
</p>

```c#
    public class Human : Sleep
    {

    }
```
<br>
<p>
Now the <b>Human</b> class is capable of sleeping whenever <b>GetSleep()</b> is called over any human subject, Let's do that in a class called <b>Night</b>. Because the night cycle is one of the pottential triggers for Humans or any living organisms to sleep.
</p>

```c#
public class Night : MonoBehaviour {
 private GameObject human;

    private void PutEverybodyToSleep()
    {
        Sleep sleep = human.GetComponent<Sleep>();

        if(sleep != null)
        {
            sleep.GetSleep();
        }
    }
}
```
<p>
Here we have a <b>GameObject</b>(<i>An <b>Unity</b> centric object, It serves as just a reference that holds the class <b>Human</b> over it</i>). Now we do a <b>GetComponent</b> to get an instance of the <b>Sleep</b> from the <b>Human GameObject</b> and if it actually has an instance of <b>Sleep</b>(<I>we confirm it by doing a a null check</I>) we call the <b>GetSleep()</b> method to put the human subject to sleep. Since the <b>Human</b> class directly inherits the <b>Sleep</b> the <b>GetSleep</b> method had become part of the <b>Human</b> class.
<br>
As you have seen the <b>Human</b> class has nothing written in it, All it did was inherit a <b>Sleep</b> class into it and all of <b>sleep</b> functionality came on to it for the <b>Night</b> class to call it. 


</p>
<br>
###I promised right through the read that I will answer the following two questions in no chronological order.
1) The comment of <b>GetSleep()</b> inside the <b>sleep</b> class saying,<I> "the inherited organisms will sleep whence this method is called" </I> 
2) Why abstract intstead of a normal class ?

I will answer the <b>first question</b> first, The reason to say that the inherited organisms instead of an organism because we were only talking about a human at that point of time and this <b>GetSleep()</b> was not just built for humans. The <b>GetSleep()</b> method inside the <b>Sleep</b> class upon inheriting will be a generic method that puts any organism to sleep as "<I>sleep</I>" is a common behaviour for all living organisms. So we can just inherit this class on any class types that require sleep behavior.
<br>
Before answering my <b>second question</b> I would like to remind you again that an abstract class is very similar to a normal class. Both are capable of handling a <b>constructor</b>, both are capable of creating <b>local/global</b> variables inside (<I>just like the <b>sleep</b> boolean inside the <b>Sleep</b> class</I>), both are capable of <b>encapsulating</b>(<I>hiding data from children classes or other unrelated classes</I>) both member variables and methods inside a class. The last and the most important similarity in both types of classes are, they are capable of handling <b>virtual methods</b>.
<br>
###Wait! what are virtual methods?
<p>
Virtual methods are like any other method where they will have a method definition and will execute that definition upon calling that method. As an added advantage, If these methods are being inherited from a <b>parent</b> class these classes can be modified in the <b>children's</b> class by adding new definitions along with the existing definition or one can even over-write the entire definition provided by the parent class with a new set of definitions by using the <b>"override"</b> keyword.
</p>

### Let's write a short virtual method inside our sleep class
<p>
To make any method a virtual method add the <b>"virtual"</b> keyword after an access specifier and before the return type of a method. Here in our example, there is a <b>Dream</b> method that generates <I>a basic not so nightmarish, non-eccentric dream</I> upon called by any of the children's class instance. 
</p>

```c#
public abstract class Sleep : MonoBehaviour
    {
        public bool sleep;

        public void GetSleep()
        {
            //the inherited organisms will sleep whence this method is called
            sleep = true;
        }

        public virtual void Dream()
        {
            BasicDream();
        }

        private void BasicDream()
        {
            //A basic not so nightmarish, non-eccentric dream  
        }

    }
}
```
<p>
It is not mandatory for the children class to override the virtual method.
</p>
```c#
 public class Human : Sleep
    {
        public void GetSleep()
        {

        }

    }
```
 
<p>
This should not throw you any compile time or run time errors, but if you'd like to change the definition, You're given a free hand to do so. Let's assume that our human subject is suffering from some sort of sleep disorder and has a hard time sleeping. We cannot expect our subject to be having a pleasant dream during the course of his slumber. So we override the existing <b>Dream</b> method to give him a nightmare.
</p>
```c#
public class Human : Sleep
    {
        public void GetSleep()
        {

        }

        public override void Dream()
        {
            //bring him some ghosts, clowns and zombies to wreck his sleep
        }

    }
```
<p>
Now if you call the <b>Dream()</b> for an instance of a <b>Human</b> class, This human instead of having a non-nightmarish dream, he will see ghosts, clowns, and zombies in his dreams.
<br>
Here we have overridden the previous definition and changed it to give our human subject a taste of hell. But don't you feel like we have been too hard on our test subject? I definitely feel like it. So let's give him a normal non-nightmarish dream after all of that nightmare. As you know this "<I>non-nightmarish dream</I>" functionality is already part of the base <b>Dream()</b> method definition situated inside the parent class <b>Sleep</b>. Thus we do not have to rewrite it. To call the base definition inside an overridden method just use the keyword <b>"base.MethodName()"</b> (<I>in our case it is base.Dream()</I>) to use the base definition written inside the parent class.
</p>
```c#
        public override void Dream()
        {
            //bring him some ghosts, clowns and zombies to wreck his sleep
            base.Dream();
        }
```
<p>
The base class can be called inside an overridden method in no particular order. It can be either called before the overridden definitions or in-between the overridden definitions or even after the overridden definitions as we did above.
</p>
<br>

###Now that you've learned virtual methods, we can now continue with answering the second question which is "Why abstract class instead of a normal class"?
<p>
As you could see normal classes and abstract classes are very similar and there is only one reason that should probably make you use an abstract class instead of a normal class. It is the need for an Interface like methods. In an Interface, methods are just declared and not defined. The ability to define these methods will be made mandatory for the classes that inherit the interface. The same way we can create such methods in abstract classes by preceding the method with the <b>"abstract"</b> keyword. Just add <b>"abstract"</b> keyword after an access specifier and before the return type of a method to make a method an abstract method.
<br>
<br>
We now use the same old <b>Sleep</b> class to create an abstract method called <b>EstablishSleepTime()</b>. As you could see that the sleep time can change in between species to species, every species should be able to establish their own definition of managing their sleep time. 
<br>
Remember these abstract methods will not have definitions inside and the compiler will throw an error even if you try to give one. 
</p> 
```c#
public abstract class Sleep : MonoBehaviour
    {
        public bool sleep;

        public void GetSleep()
        {
            //the inherited organisms will sleep whence this method is called
            sleep = true;
        }

        public virtual void Dream()
        {
            BasicDream();
        }

        private void BasicDream()
        {
            //A basic non nightmar-ish, non eccentric dream  
        }

        public abstract void EstablishSleepTime();


    }
}
```
<p>
And also remember that the <b>abstract methods</b> can only be written in an <b>abstract class</b>.
</p>
<p>
Whence this class is inherited, the inherited class (in our case the <b>Human</b> class) will have to establish the amount of he sleep any human should be getting. 
</p>
<p>
<I>Writing definitions for an abstract method can only be done by overriding the abstract method inside the inherited class just like overriding a virtual method inside an inherited class</I>
</p>

```c#
    public class Human : Sleep
    {
        public void GetSleep()
        {

        }

        public override void Dream()
        {
            //bring him some ghosts, clowns and zombies to wreck his sleep
            base.Dream();
        }

        public override void EstablishSleepTime()
        {
            //get 8 hours of sleep for this human
        }
    }
```
<p>
Here inside the <b>EstablishSleepTime()</b> method we define the amount of time a human can sleep. Since this <b>EstablishSleepTime()</b> is made as an abstract method in the parent class this method is made as a mandatory class to be defined in the children's class. 
</p>

###This is the main reason why we use an abstract class instead of a normal class.

<p>
<b>The other main use of an abstract class:</b>
<br>
If you could see the abstract class <b>Sleep</b> you can witness that it is a very common behavior of every living thing. Even non-living things like computers sleep when they're tired. So this functionality can be inherited by any class that requires sleep. If you had written the sleep functionality inside every single class it would only be a duplicate of the same functionality inside every single class that requires sleep. Since abstract is capable of being a replacement of a normal class, We write this once in a class and we directly inherit it and use it anywhere like how we would do with a normal default class.
</p>
###Conclusion
<p>
Abstract classes are a combination of both a normal class and an interface. A normal method cannot handle an abstract method and Interfaces are incapable of using constructors, encapsulation, member variables, and method definitions. But the abstract class is capable of doing what both of these classes cannot do. If your class structure demands for such a class to be inherited then you should use an <b>abstract</b> class.
</p>