Object oriented programming has a few core concepts. One of the most fundamental is Inheritance. Here’s a really simple explanation:
- Inheritance is using existing classes as the foundation of new classes.
Once again, a real world example would be good here.
Let’s say you have a blueprint to create a ‘Car’. The blueprint contains instructions as follows:
- X number of wheels
- Y number of doors
- Z top speed
Then let’s say you want a new blueprint to create a ‘Fast Car’ that had an extra property of ‘Color = Red’. Do you think it’s wise to copy over the basic ‘Car’ blueprint and modify it for a ‘FastCar’ just to add the color red? Well no, you’d be repeating the same information. What if someone changes the basic car configuration? You’d need to ALSO change it for ‘Fast Car’.
Time for a code example, the basic ‘Car’:
var numWheels = 4
var numDoors = 4
var topSpeed = 100
And now for the ‘FastCar’ which inherits from ‘Car’:
class FastCar: Car
var color = "red"
Now FastCar has inherited all the properties / functions / whatevers from ‘Car’. Neat right?
So in summary, the basic idea of inheritance?
Don’t repeat code.