Inheritance - Part 2
How would you design and implement placing order with the details of all the products bought?
Composition
Modelling instances of one class as attributes of another class is called Composition
Code
Output
In the above example, we are modelling Product as attribute of Order
Overriding Methods
Sometimes, we require a method in the instances of a sub class to behave differently from the method in instance of a superclass.
Code
Output
Because
Super
Accessing Super Class’s Method
Instead of writing and methods to access and modify warranty we can override
Let's add warranty of ElectronicItem.
Code
Output
MultiLevel Inheritance
We can also inherit from a subclass. This is called MultiLevel Inheritance.
We can continue such inheritance to any depth in Python.
Inheritance & Composition
When to use Inheritance?
Prefer modeling with inheritance when the classes have an IS-A relationship.
When to use Composition?
Prefer modeling with inheritance when the classes have an HAS-A relationship.