Write a program using an object
Start to create your object-oriented text-based adventure game
Extend other people’s classes
Create an enemy in the room
Recap Week 3
Extending your knowledge of OOP
Finish your game
End of the course
Well done for completing the third week of the course.
This week, you looked at the concepts of inheritance, polymorphism, and aggregation. If you have any questions about these, or about the quiz you completed in the last step, ask them in the comments section.
When you create a subclass, that class will inherit all of the attributes and methods from the superclass. You used inheritance to extend a class written by somebody else, customising it and overriding its methods as necessary. Moreover, inheritance is also useful because it allows you to write code only once in a base class, and then extend that code with subclasses. It therefore helps you to avoid code duplication.
Polymorphism allows us to treat a subclass as if it were an object of the superclass, and yet still have the subclass behave differently. You saw this demonstrated where you wrote some code for a character object, and then successfully used the same code on an enemy object. This was possible because Enemy is a subclass of Character.
When an object contains another object, you can describe their relationship with ‘has a’, and you call this aggregation. For example, your room object now has a character inside it. In practice, the object might be of the Character class or the Enemy class: because of polymorphism, an enemy is a character, and therefore it doesn’t matter which type of object is used.
Next week, you will investigate class variables and finish writing the game. You will also look at ways of sharing your code and making it easy for other people to use.
Aggregation: when an object contains an instance of (or ‘has a’) another object
Extend: a class that uses the functionality of an existing class, but also adds to or overwrites some of it
Inherit: a class that inherits from another class is able to use all of the attributes and methods from that class
Polymorphism: if a class inherits from another class, it can also be considered to be (‘is a’) object of that class, but can behave differently
Subclass: inherits the properties of another class and adds some specialised methods of its own
Superclass: provides methods and attributes that are used by another class