Chapter 3. Inheritance: Relying on Your Parents

image with no caption

So much repetition! Your new classes representing the different types of vehicles and animals are awesome, it’s true. But you’re having to copy instance methods from class to class. And the copies are starting to fall out of sync—some are fine, while others have bugs. Weren’t classes supposed to make code easier to maintain?

In this chapter, we’ll learn how to use inheritance to let your classes share methods. Fewer copies means fewer maintenance headaches!

Copy, paste... Such a waste...

Back at Got-A-Motor, Inc., the development team wants to try this “object-oriented programming” thing out for themselves. They’ve converted their old virtual test-drive app to use classes for each vehicle type. They have classes representing cars, trucks, and motorcycles.

Here’s what their class structure looks like right now:

image with no caption

Thanks to customer demand, management has asked that steering be added to all vehicle types. Mike, Got-A-Motor’s rookie developer, thinks he has this requirement covered.

image with no caption

Mike’s code for the virtual test-drive classes

image with no caption

But Marcy, the team’s ...

Get Head First Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.