Intro to inheritance
In this article, you will get an introduction to inheritance in CSharp. This is an important concept of object-oriented programming.
Hereby we talk about parent classes / superclass and child classes / subclasses. Here is a small example
The superclass car inherits to the two subclasses BMW and Audi. These two subclasses now have access to all the functions and variables of the superclass car which are public. The superclass car now has a function called repair() . This function should simply write something into the console, then we can use this function by objects of type BMW and Audi.
To get a (sub) class from another (super) class, you have to append the superclass to the class name of the subclass. So Audi: Car
Example of inheritance in CSharp
class Programm { public static void Main(string[] args) { Audi A4 = new Audi(); BMW M5 = new BMW(); A4.rapair(); M5.rapair(); Console.ReadLine(); } } class Car { public void rapair() { Console.WriteLine("The car was repaired!"); } } class Audi : Car { } class BMW : Car { }
Although the two subclasses Audi and BMW have no content, we can still create objects from them and use the repair function (). This is because they have inherited this function from the carclass. Now, if we want the function to repair () to call on an AudiObject, we need to declare the function repair () in the subclass Audi that does that. And basically overwrite the original function.
class Audi : Car
{
public void repair()
{
Console.WriteLine("The Audi was repaired!");
}
}
Output: The Audi was repaired!
Advantages of inheritance
- Basis for polymorphism – more in the chapter on polymorphism
- Reusability
- No source code duplication necessary
- Error corrections or changes to an upper class will automatically affect all subclasses as well
- Less typing
- Easier cooperation
Please note!
If we were to add a parameter to one of the subclasses (this approach is called “overloading”), it would be a completely new method and not the same method we have in the superclass.