Inheritance is one of the core fundamentals of OOP. Learn how you can write more DRY code in utilizing it in this video.
- Although everything in this course is important, inheritance is probably the most important aspect to object oriented programming if had to pick something. So pay special attention to this section. We're going to be using some graphics here to just give a very high-level overview of how inheritance works. And then of course, we'll be diving into many code examples after this. So let's say that we had a base class of animal. Sometimes you'll hear our base class referred to as a parent class. And the idea with parent classes that you're going to inherit from is that it's really a contract to say this is how my children are going to work or my derived classes. So with an animal class, you might have an animal that's seven and it has four legs and their name is Gator. My dog's name is Gator. But the idea is that we have an animal. Now, as we go and we decide what type of pets that we have, such as a dog class or a cat class, those are our children classes that are inheriting, or implementing, our animal class, oftentimes referred to as derived classes. The idea here is that, although we don't necessarily create a single animal class, we are going to have dogs and we are going to have cats, but they're going to have some things in common and we want to make sure that that contract, or the understanding of the code, if you want to think of it that way, is that they're in sync. I want to make sure that our dog class and our cat class have an age property, a leg property, a name property, and then they can have their own specific properties, or even methods, such as woof for a dog or meow method for a cat that they can go and do. It's one of those things where now everything's in sync, we know how it's going to work, and we don't have to repeat ourselves. It keeps our code dry and easy to use. Let's go ahead and look at some code examples.