A quick video from me to start Day 3.
Introducing Inheritance
00:00 So after yesterday’s detour into looking at the object, we’re back to reviewing object-related programming. And today we’re going to talk about inheritance.
00:08 So creating a class is creating a template for some, either some real-world object or entity, but it doesn’t have to be real-world. It could be an abstract concept as well.
00:22 But you have something that you want to model and you create a class. You’re creating a data type that’s particularly suited for the thing, real-world, like more abstract concept that you want to model.
00:37 But often you also want to create a class. You also want to model something which is similar to something else. In fact, you want to model something which is a subset of something else.
00:48
An example that’s often given, one that you see in one of today’s lessons is, let’s assume you have a class for Animal
, which describes what an animal does and what you can do with an animal.
01:00
But then you want to create a class called Dog
. Well, a dog is an animal. You don’t want to create two separate classes. Why? Because there’s going to be lots of repetition between them.
01:09
So you want to create the Dog
class that starts off as an Animal
, and then you can add more characteristics to it. You can customize the Dog
class further, but that means that you don’t have to do everything from scratch.
01:24 And this is what we call inheritance. In fact, we often use the parent class and the child class terminology, which sort of makes sense. The child class inherits from the parent.
01:35 Although the analogy may not be perfect because in object-oriented programming, the child class inherits everything from the parent. And then you can of course make changes.
01:44
Another example you see in today’s lessons, for example, is, is an Employee
class. So you’ve created a class for an employee, but then you might have a slight difference between salaried employees and maybe contractors.
01:58
You don’t want to create separate classes. You want both of them to inherit from the Employee
class at the top. One final thing, inheritance.
02:06 When people first master inheritance, it’s tempting to use it for everything. Like many tools in programming, and we can discuss this further in our live sessions and in the forum, inheritance is one of those tools where it’s important to know it.
02:21 It’s a great tool to use, but you don’t want to overuse it either. And one of the last lessons today will compare inheritance with another technique we can use, which is called composition.
02:33 And one thing you want to learn with time is when to use one technique and when to use the other technique. This applies to many things in coding, but in this particular case today, we’ll compare inheritance and composition.
You must own this product to join the conversation.