A4 - Inheritance
In this assignment, we'll look at basic class inheritance.
When you create a class, you can choose to make it an extension of an existing class by using the extends
keyword as follows:
In the example above, Cow will be a child class of Animal. This means:
- All the methods in the
Animalclass will also be available in theCowclass - If the
Cowclass does not define a constructor, the constructor of theAnimalclass will be used forCowobjects - If the
Cowclass does define a constructor, it can all the animal constructor using thesuperkeyword (as you'll see in the full example) - The
Cowclass can override any methods defined inAnimalto give them custom behaviour - The
Cowclass can also define it's own additional custom methods
Full Example
Run the update, then look for a new a4 folder inside Unit 4.
Start by exploring inside the sample subfolder.
Run index.html using Live Server, and read through index.js.
The sample contains a full example with lots of commenting to explain it through.
Your Task
Just like the previous assignment, within the root of the a4 folder there is a generic example to get you started with.
Modify it so that it represents something real.
You will need to decide on a base class that will represent something generic, and two child classes that represent
something more specific within the category of the base class.
For example, you could say:
- Base class is a
Vehicle - One child class is a
Car - Another child class is an
Airplane
Start by adding some methods to your base class. At least one should be intended for your child classes to override, and at least one should be intended for your child classes not to override. For example, using the vehicle example,
- You could have a method called
moveForward(speed)that none of the child classes override, since moving forward is pretty much the same for all vehicles - You could have a method called
slowDown()that each vehicle overrides, since they slow down in different ways (a car applies the brakes, a plan will adjust the throttle)
In each of your child classes, override the method you had intended to.
In at least one of your child classes, create a custom method.
For example, we could add a takeOff() method into our Airplane class.
Finally, add some code outside your classes to try it all out. Create an instance of each class and call each of the methods, similar to what you see in the example.