Inheritance#
Objects are often very similar. They share common logic. But they’re not entirely the same. Ugh… So how do we reuse the common logic and extract the unique logic into a separate class? One way to achieve this is inheritance. Inheritance allows classes to inherit features of other classes. Put another way, parent classes extend attributes and behaviors to child classes. Inheritance supports reusability – if basic attributes and behaviors are defined in a parent class, child classes can be created extending the functionality of the parent class, and adding additional attributes and behaviors.
Let’s say that teachers and students are a special type of person that have subjects to tech and learn and few more information and behaviours. We can create child classes Teacher
and Student
from the parent class Person
, and then add behaviors. The benefits of inheritance are programs can create a generic parent class, and then create more specific child classes as needed. This simplifies overall programming, because instead of recreating the structure of the Person
class multiple times, child classes can extend the functionality of a parent class.
Benefits of inheritance:#
Code reuse: create generic classes, and then create more specific classes as needed which inherit from generic classes
Code organisation: inheritance makes you think about structures of your in term of generic to specific objects