10.5 Applications
Inheritance is a way to form new classes that borrow attributes and behaviors of previously defined classes. After learning about inheritance and method overriding, you are probably wondering when you will ever need to use them. What is the big deal about inheritance? Why can’t we just make a bunch of different classes? To put it simply, it saves significant unnecessary coding by eliminating code duplication, and it simplifies software testing and maintenance since functionality and local data are isolated. Here are several other examples for which you can use inheritance.
10.5.1 Person Database
A contractor is looking for a way to keep track of all the people
in his organization. He has full-time and part-time employees, student
interns, and volunteers. In this example, you can make a class called
Person
. This class can have the
individual’s name, address, phone number, email address, and weekly
hours worked. You can have a method called email
that emails all the employees to remind
them to turn in their time sheets. Then you can have subclasses called
Full
, Part
, Intern
, and Volunteer
. For the Full
subclass, you can include variables like
hourly wage and overtime pay. For a behavior you can have a process_payment
method to deposit money into
the employee’s bank account. A student Intern
would have different variables. Maybe you want to keep track of who has the highest grade-point average or test scores to see which one is the top intern. Thus, you would ...
Get Computer Science Programming Basics in 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.