Continue your journey by learning about subclasses and inheritance. In this lesson, Steve breaks down how classes can reuse data to expand on a class using less code.
In the last lesson, we created an instance of a class by choosing properties and behaviors for our characters. With subclasses and inheritance, we are able to extend the properties and behaviors of a class without having to rewrite the class. By inheriting the properties and behaviors of our base class, we can add to the existing class or override properties and methods that already exist. Choose a character below to upgrade your attack capabilities!
A lot of new terms were presented in this lesson. Have a look before you take the quiz!
A base class is a class that other classes use to inherit properies and behaviors. Using a base class allows us to reuse code through the process of inheritance. Our characters have the base class PLAYER, and are also base class of the characters ELF, WIZARD, ORK and KNIGHT after we upgrade
A subclass is a class created specifically to inherit properties and behaviors from a base class. We used subclasses to upgrade our character's attack data without having to rewrite the character class with inheritance.
Inheritance is the process that allows us to derive a class from another class, in which the properties and methods of the derived class are available to the new class. We used the base class PLAYER to pass on life and Tolkiens to each of our character classes. Additionally, we created an UPGRADE class to inherit from our character class so that we could override the attack behaviors with new and improved weapons.
Overriding allows subclasses to replace behaviors that are already defined in a base class with specific implementation for the subclass. When we upgraded our character, we replaced the weapon for attack by overriding the base class weapon.
Are you ready to see what you've learned? Take the quiz below to see if your ready to move on to the next lesson!
Before moving on to the next lesson, take some time to think about how you can reuse your classes by breaking them up in ways that can be inherited by other classes. In this lessons video, for example, Steve mentioned how your phone can be upgraded. You could have a phone class that has the basics of what phones do. For instance, a phone makes calls, receives text messages and has a screen. You can override your phone by adding methods and properties that make it YOUR phone, like your contacts, your apps, or your photo library.
Join the OOP Fundamentals forum and join the discussion or ask a question!
Traveling to the halfway mark of our quest, which happens to be the realm of the elf, we'll explore how objects can have variation but still work in our game, a concept known as polymorphism.