C# Inheritance Tutorial

Definition

Inheritance is a method used in OOP which consists in creating classes derived from a base class. Basically, you’ll have a base class which ‘shares’ it’s methods with all the derived classes.

Simple Inheritance

To create a derived class from a base class you have to use something like this:

Example : It might be easier to understand this concept by looking at a practical way to use inheritance.
  • • let’s say we have a base class called vehicles that has 2 functions (spawn & despawn)
  • • we want to create from that class some new particular classes (car & plane)
  • • we also want our new classes to have those 2 functions
This is how you can do this:

To see how this works, just create 2 objects, and call those 2 functions:

Surprisingly, you can call the functions even if they aren’t directly declared in the derived classes: that’s inheritance.

Overriding methods

If you understood the way inheritance works, we can go to something more complex: overriding. It’s not very complicated: by using overriding we can customize the inherited functions: basically we can directly change their code and the way they work.
Note: a function can be overrided only if it’s marked as virtual in the base class. Overriding is done by placing the modifier override in the method’s header:

You’ll have something like this:

As you can see, the 2 functions (spawn & despawn) from the class vehicle (the base class) are marked as virtual: they can be overrided. Any derived class can customize the functions by applying the override modifier.
base.spawn() and base.despawn() are used to invoke the original functions: the ones from the base class. However those are not absolutely required in derived classes.
If we instantiate 2 objects and call those functions like in the code below:

The output will be:
Spawning a vehicle…
Spawning a Car!

Spawning a vehicle…
Spawning a Plane!
Despawning a vehicle…
Despawning a Plane!

The End!
Previous
Next Post »