If you've gotten into the world of programming, you've probably heard the term inheritance. For some reason, this term is hard for people to explain but easy to understand. So here's an explanation of inheritance that actually makes sense. |
Think about yourself and your parents. Odds are that you've heard you have certain features that are really similar to your parents. Maybe you have your dad's eyes and your mom's nose. Those are inherited traits. You have them because your parents have them.
It's the same in programming. You can have a class that gets properties and methods from another class. Say that you have a class that describes cars. It has properties for the number of doors, the type of engine, and the make and model. Now let's say you want to make a new class that only describes cars made by Audi. You still need to know how many doors the cars have and their engine type and model.
To save yourself some time, you can inherit those properties from the car class in the Audi class.
You can see that inheritance is pretty straightforward. If there are certain properties or methods you want to use in class, you can get them from an existing class. When you make a new class using inheritance, the new class is called a derived class. That's because it is using bits and pieces of other classes. The existing class is called a super class. A super class is a class that doesn't inherit from any other classes.
The beauty in a derived class is that you can always keep it up to date with the super class because any changes you make to the super class will be automatically applied to the derived class. Another reason derived classes are beautiful is because they can have all of the super class properties and have their own properties and methods.
Just like with you and your parents. Sure you have some similar traits, but you still have unique features of your own. You might be tall and both of your parents are short. You might be more outgoing than your parents. Whatever it is, you have something that no one else has. The same can apply to classes.
For example, in the Audi class you might want to include the year of the car and a method to calculate how many miles per gallon you get. You can include those things without changing the car class. All you have to do is include them in the Audi class and you're done. That doesn’t take away any of the inherited properties and they are unique to the Audi class.
Just remember, inheritance means you can use all of the properties and methods in one class in another. Any changes you make to the super class will be inherited by all of the derived classes. Also, derived classes can have their own unique properties and methods.
Thanks for reading and I hope this made sense of inheritance!
Related Articles -
programming, beginners, web development, inheritance,