Multiple inheritance
hard 50 minA class with several parent classes gets the types, the methods and the fields of all of them.
Watch lesson4:37
When it comes up
The moments this idea belongs in a design interview, and the moments it does not.
Signals
When this comes up
| You hear | Say | Because |
|---|---|---|
| A teaching assistant is a student and staff | Can either end? | Then roles, not parents |
| All our views need login and paging | Mixins on the left, cooperative | Independent abilities |
| Printer and scanner in one device | Do they share method names? | Two promises, one word |
| In Java please | One class, many interfaces, parts for state | No second parent |
| Why not just use Python's feature? | Show the order and the constructors | The price is there |
Saying it in the room
Interviewer
You have Student and Employee. Now some students work here.
You
The short answer is a class with both parents. Before that: can a student stop working and stay in the system?
Interviewer
Yes, all the time.
You
Then I would not use inheritance. Person holds roles, and a role has a start and an end. Payroll asks for the employee role.
Interviewer
Suppose it cannot. Would you use two parents?
You
In Python yes, with keyword constructors that pass the rest on, so that Person is set up once. In C++ I would make Person a virtual base and say that Student's author must have known this. In Java: one parent and two interfaces.
Teaching assistants are students and staff. Model them.
BreaksCopy the staff fields into Student
- How
student.salary, empty for most.- Limit
- Every student has a salary field, and payroll must filter.
- Choose when
- Never.
WorksTwo parents
- How
class Assistant(Student, Staff)with a shared Person.- Limit
- For life, and one join class per combination.
- Choose when
- Sides never end, and there are two of them.
StrongOne person with roles
- How
- Person holds StudentRole and StaffRole with dates.
- Limit
- Callers ask for a role and must handle absence.
- Choose when
- Real people.