I will be discussing inheritance for part two of my Object Oriented Programming series:
- Inheritance – Current Blog Post
- Polymorphism – Future Date
- Encapsulation – Future Date
If you’re not already familiar with abstraction, I recommend reading part one of my series before moving further. It is a concept that will help you understand inheritance.
What is Inheritance?
Imagine you have a Yorkshire Terrier class. When you create a Yorkshire Terrier object, the object is inheriting from the Yorkshire Terrier class. The object has the same properties and methods as the class. For example, every Yorkshire Terrier object has the same hair color and type.
What if you decided to add other Terrier classes, such as the West Highland White Terrier class. They share many of the same fields and functions, such as being able to catch vermin, having the same hair type, and sharing similar body structure. Both classes can inherit from one class – the Terrier class. This way, each type of Terrier can have its own unique methods and fields (such as different hair color), but also be able to share the same methods from the Terrier class.
What if we wanted to add a different type of dog? How about a hound? This is where an interface comes in handy. You can create a Dog interface. When a class inherits from an interface, it must implement all methods and fields of the interface. I will discuss more about interfaces with the next OOP topic(Polymorphism), but for now, think of the interface as a way to group multiple classes together.
Inheritance cuts down on duplication by allowing you to keep similar functions and fields in the same location. It also helps keep your code structured. Imagine having multiple, distinct terrier classes that inherited from no class. Whenever you want to make a change to certain core Terrier qualities, you would have to modify every terrier class. However, if you used inheritance, you only need to modify one class – the Terrier class, which will affect all the classes inheriting from it.
Thus, whenever you start to see duplication between classes, it is a sign that you should start considering inheritance. Try finding ways to implement inheritance in your code.