C# language: 13. Abstract classes

In the lesson on interfaces, I said that I will say about abstract classes, this is the lesson.

So what are the abstract classes? As in the case of interfaces, we can not create a class object, but why do we need such a class if we can not create its object? Abstract class works like the interface with the difference that what is in the interface must be in the class assigned to this interface, and in the class that inherits from the abstract class does not have to be everything that is in the abstract class though it may be. Only definitions of methods and abstract fields must appear.
Let’s change the Cake class for an abstract one, do it like this:

No errors come out because the abstract class behaves like ordinary classes with the difference that we will not be able to create a Cake class object now. However, if we have several classes that will inherit from the abstract class and the method that is in the abstract class will be changed in all derived classes (ie, inheriting classes) then you must create something like this in the abstract class.

Abstract methods look like that without a body and instead of virtual word we put abstract word

And the implementation the test method in the class that inherits from the abstract class looks like this:

And so we do in every class that inherits from the abstract class, the word override is always crucial for abstract methods, although we do not overwrite anything, but in the abstract method there is nothing to overwrite.

It must be remembered that the abstract class should have at least one abstract method, and that the abstract method can not be static (i.e., no static words can be added).

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-13-abstract-classes

And on medium: https://medium.com/@sawomirkowalski/c-language-13-abstract-classes-6d82bb116490

That’s all for today, in the next lesson we will learn the so-called collections!

If that post was useful for you share it with your friends :)

Post a comment

Notify about