Classical inheritance – C#
Let’s start with an example of classical inheritance in C#. There is a class with public and private data and a subclass which inherits some properties and wants to call base class’ members. Also we want the type system to be aware of types and properly recognize whether or not an instance belongs to a particular type. Specifically: an instance of the base class should not be recognized as and instance of the child class but the instance of the child class has both the child type and base type.
The output of this code is
I’ve found these tutorials to be helpful:
- Why Prototypal Inheritance Matters by Aadit M Shah
Start by reading these and come back when you finish.
The constructor inheritance is a technique where a function, whose name starts with an uppercase letter by convention, acts as a constructor. You have to remember to call it with new to get a new instance. The newly instance “inherits” properties from a so called prototype chain which basically means that there is a list of known instances which play the role of prototypes.
- in a Protype design pattern you have a prototype instance of an object and you use to create new objects out of by cloning the prototype
The constructor inheritance snippet is:
- there is no constructor function, rather there is an explicit instance of the prototype
- instead of new we are using Object.create which creates a new instance out of the given prototype
- instead of constructor function we have a factory method which can possibly call the factory method of the base class
- because there is no constructor function, instances cannot be tested for being a particular type with the instanceof operator; rather – an extra method is provided
- an auxiliary function extend is introduced which clones the prototype of the base class as the prototype of the child class