C# language: 11. Inheritance

Object-oriented programming consists of four main elements, encapsulation, inheritance, polymorphism and abstraction, encapsulate is behind us time to get to with inheritance and polymorphism.

1. What is inheritance?

What is inheritance? Let’s assume that we want to make a recipe similar to the one we made earlier, we will add only a few additional ingredients to this new one, so the new recipe will also have a list of ingredients from the previous one, so why prescribe cake code from the first cake? We will also use the third most important protected access modifier.

So let’s create a new class for a new cake as we did in the first lesson about classes and call it NewCake. If we want the NewCake class to inherit from the Cake class, we need to write something like this next to the name of the NewCake class:

When we do that, we will have a bug related to the Cake class constructor, but we will worry this later

First, let’s set the Cake class property to the protected access modifier so that it is available only for the NewCake class, and add new fields and properties for the NewCake class. Let them be the AmountOfSpices and AmountOfSugar fields, and set it to protected, we will call these fields using methods

Now you have to correct the error related to the constructor, let’s add something like this to the NewCake class:

Already explaining what is it with the constructor, is not subjected to inheritance in the base class, in brackets next to the NewCake class name we must provide all arguments from the base class as well as from the inheriting class and in parentheses with the word “base” we must specify all variables from the constructor from the base class

Now the Cake and NewCake classes look like this:

We can also extend existing methods from the base class, but in order to do this we must add before the type of function that we want to extend the “virtual” word in the base class and in the inheriting class or derivative we adding word “override”, I have expanded the method from the Cake class like this:

line base.PourSalt (); I call this method from the base class and I have extended this method in the NewCake class with such a line “Console.WriteLine (” And some sugar “+ _ AmountOfSugar +” g “);”

I mentioned earlier in previous lessons about the access modifier with the words “sealed”, when you use it in some class, it will not be inherited, so it looks like:

When you use it, the mass of errors will appear.

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

And on medium: https://medium.com/@sawomirkowalski/c-language-11-inheritance-9dc1844bb448

I think I’ve explained the basic aspects of inheritance well, that’s it, see you!

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

Post a comment

Notify about