C# language: 13. Abstract classes

in #programming6 years ago

CC.png

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:

abstract class Cake : ICake

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.

public abstract void test();

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:

public override void test()
{
    Console.WriteLine("This is NewCake class");
}

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 blog http://devman.pl/csharplan/c-language-13-abstract-classes/

If you recognise it as useful, share it with others so that others can also use it.

Leave upvote and follow and wait for next articles :) .

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

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.033
BTC 63464.16
ETH 3111.33
USDT 1.00
SBD 3.98