- LPU MCA Semester 1
- CAB106
- Unit 3
CAB106 · Unit 3: Encapsulation, inheritance and polymorphism
Types of inheritance: single, multiple, multilevel, hierarchical and hybrid
11 practice questions
Key points
- Single, multiple, multilevel, hierarchical and hybrid
- A child __init__ must call super().__init__() to run the parent's
- MRO is searched left to right with shared parents last
- super() follows the MRO, not just the direct parent
Inheritance lets a child (derived) class reuse the attributes and methods of a parent (base) class. The syntax is class Child(Parent):.
| Type | Shape |
|---|---|
| Single | One child, one parent |
| Multiple | One child, several parents |
| Multilevel | A chain: C from B from A |
| Hierarchical | One parent, several children |
| Hybrid | A mix of the above |
A child that defines no __init__ uses its parent's. A child that defines its own __init__ replaces it, so call super().__init__() to run the parent's constructor; otherwise attributes created there never exist. Python resolves names through the method resolution order (MRO), available as Class.__mro__: the class itself, then its parents left to right, with a shared parent placed after all classes that derive from it, and finally object. In a diamond D(B, C) the MRO is D, B, C, A, object. super() means the next class in the MRO, not simply the parent.
isinstance(obj, A) is True for objects of subclasses, but sibling classes are not instances of each other.
Exam trap: with super() in a diamond every class runs exactly once, in MRO order, so super() in B can reach C.
Try two questions
Which description fits hybrid inheritance?
- A child class that has no parent defined in the program
- A parent class that cannot be instantiated by any program
- A class that copies the methods of another by value
- A combination of two or more inheritance types in one design
Show the answer
D. Hybrid inheritance mixes types such as hierarchical and multiple.
Why not A: Every class has a parent, at least object.
Why not B: That describes an abstract class.
Why not C: Inheritance shares behaviour by lookup, not by copying.
Class C derives from class B, and B derives from class A. What is this arrangement called?
- Multilevel inheritance
- Hierarchical inheritance
- Multiple inheritance
- Single inheritance
Show the answer
A. A chain of derivations across generations is multilevel inheritance.
Why not B: Hierarchical inheritance has one parent with several children.
Why not C: Multiple inheritance has one child with several parents.
Why not D: Single inheritance is only one parent and one child, without a chain.