So far, we have only introduced convenience features of OOP. Sure, packaging and reducing subroutine name clutter are nice features to make programmer cleaner and more bug resistant. However, can OOP offer any more than these features?
The other advantage of OOP is ability to reuse old definitions with minimal work. This is just the beginning of advantages of OOP!
Let’s think about questions in a test. There are different types of questions, such as “essay”, “multiple choice” and “fill in the blank”. Following our example, it makes sense to define a class for each question type. As a result, we end up with the following classes:
However, it’d be a chore to copy-and-paste all the common properties of the class “Question” to each specific question type. Chore means tedium, tedium means more room for error. OOP eliminates the chore using inheritance.
Using OOP, a program declares that “EssayQuestion is a sub class of Question”. This is a fancy way to say “EssayQuestion automatically includes all the properties and subroutines of Question”. This statement by itself isn’t very powerful. However, we can also say “MCQuestion includes all the properties and subroutines of Question”.
You can imagine how much typing is saved if a class has many subclasses!
The advantage does not stop here, either. Because EssayQuestion is a subclass of Question, a programmer can extend and specify more properties and subroutines in Question. As a result, all subclasses of Question immediately gain all these new properties and subroutines.
Without the concept of inheritance, there’ll be a lot of copying and pasting. Now repeat after me: “copy-and-paste is evil!”. Why? If the original code has a bug, then all copies must be fixed. It is easy to lose track of the the clones after a while, and the forgotten clones don’t get fixed!
Inheritance is one of the core features of OOP, regardless of the programming language. It can be combined with other concepts (such as overloading and virtual methods) to make classes even more flexible and reusable. However, even in the most static way, inheritance is already quite a powerful feature.