Inheritance


Collapse Content

In the last node, you saw how different car instances can be created from one Car Class without having to re-write any code. But what if you wanted to create another car that was similar but needed a modified template? For example, you might want to create some of the following:

  • 2 different racecars, like a Formula 1 Racecar and a Rocket Car.
  • Consumer cars, like the Toyota Camry and a the Ford Explorer.
  • Other vehicles, like Trucks and Motorcycles.

Each type of vehicle will overlap in many ways, but also have different types of state and actions. For example, a Motorcycle can do a wheelie, while a truck can attach another cart behind it. Since each instance of a Class follows the same template, these different vehicles cannot belong to the same class. Another approach is needed.

Inheritance
Inheritance means different classes can inherit the state and behaviors of another class. They can modify what they inherit and add their own new methods and states. For example, cars, trucks and motorcycles could all inherit from a Vehicle class, since they all share certain methods and state, such as accelerate() and speed. Below is an inheritance chart of different classes, and their methods and variables. A class inherits all the methods and variables of its ancestors. For example, a FordExplorer Object will have access to the powerLocks variable of Car and the accelerate method of Vehicle.

chart-of-veichle-inheritance

Challenge

According to the above chart, a ToyotaCamry Object will have all of the following methods EXCEPT ___ ?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

Contact Us
Sign in or email us at [email protected]