AlgoViz

Multiple inheritance

hard 50 min

A 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 hearSayBecause
A teaching assistant is a student and staffCan either end?Then roles, not parents
All our views need login and pagingMixins on the left, cooperativeIndependent abilities
Printer and scanner in one deviceDo they share method names?Two promises, one word
In Java pleaseOne class, many interfaces, parts for stateNo second parent
Why not just use Python's feature?Show the order and the constructorsThe price is there

Saying it in the room

  1. Interviewer

    You have Student and Employee. Now some students work here.

  2. You

    The short answer is a class with both parents. Before that: can a student stop working and stay in the system?

  3. Interviewer

    Yes, all the time.

  4. 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.

  5. Interviewer

    Suppose it cannot. Would you use two parents?

  6. 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.