4D v18 R3 gives us another way of writing cleaner, more reusable code by introducing class inheritance. A class that is created with class inheritance receives all the functions from another class. This is useful when you want to create a new class that is very similar to an existing class with only minor differences. For example, let's imagine that we have the Car class below:
It has two initial properties, "make" and "model", and also two functions that alert different messages, soundHorn and turnLeft. Now, let's say we want to create a Van class that inherits from the Car class, since a van is essentially a car. To do this, we need to use the new Class extends command:
By saying that the Van Class extends Car class, we indicate that the Van class will have all of the aforementioned properties and functions of the Car class. We do not have to re-write the code for Class constructor, soundHorn, or turnLeft, to allow Van objects to access all the same functionality as Car objects.
Now, let's say that we want to add a third property called "size" that is set to "HUGE", to indicate that vans are larger than regular cars. A new class contructor must be written like below:
The Super command must be called in the constructor, before any new properties utilizing This are added, to indicate properties and methods are accessed from the parent (super) class. Functions of the parent class can also be overriden by simply writing a new function with the same name. For example, let's say that we want to override the turnLeft function for the Van class like below:
Instead of a generic message, we want the alert message to be customized to the type of vehicle. Now, to bring it all together, we can create a new Van object:
And when we test our two functions, soundHorn (inherited) and turnLeft (overridden), we respectively get these messages: