Single Inheritance

From Director Online Wiki
Jump to: navigation, search

With single Single Inheritance you can create a straight line of inheritance - where every inheritant can have only one direct ancestor.

The relationship between the ancestor and the inheritant should always be a "Is-a"-relationship.

Basic example

You want to create a game where you have a Car and a Motorcycle. You could do the behaviours of the two as completely seperated scripts - but this would mean that you have duplicated code. Both have obviously similar things - like wheels, and they both need fuel.

You could create one behaviour for both together - but then you have to create many if-then's, to seperate the things they have not in common - like the number of wheels, and the speed. Those many if-then's would make it harder to read the code.

This is where inheritance comes in handy - you can create one basic script called Vehicle wich defines the basic properties like the wheels, and the basic methods like drive(). Then you create 2 seperated scripts for the Car and the Motorcycle, which only include the things that only apply to these specific vehicles.

As soon as you define the ancestor in these 2 script, then they are called inheritants, and can access all properties and methods of the ancestor.

This shows the described "Is-a"-realationship - because you can say: The Car' is a Vehicle - and the Motorcyle is a Vehicle.


Advanced example

Although one script can have only one ancestor, the ancestor itself can have a own ancestor. In fact you can create a whole Ancestor Chain. Building on the first example you could create the following relationships:

Vehicle is-a Car is-a Racing-Car is-a Lamborghini

Implementation

For the implementation in Lingo see LingoInheritance, For JavaScript see JavaScript Inheritance.