Inheritance

What is inheritance?

Inheritance describes one type of relationship that can be modelled using OOP. Inheritance is best described as an is a type of relationship e.g. a dog is a type of animal. Inheritance allows a child class, also called a subclass, to automatically inherit the attributes and methods of it's parent class, also called a superclass.

The UML representation of inheritance is a line from the child class to the paret class with an arrow head at the parent end.



The parent child relationship

To create a child class of an existing class you pass the parent class as a parameter. You can preset the parameter type as cat by default and then pass one less attribute. As the cat class inherits the attributes and methods of the parent class we can call its constructor using super( ).__init__( ).

We can override the parents constructor and extend the child class with additional attributes and provide additional methods for these attributes. When designing objects using inheritance you need to consider what attributes and methods are common to all objects and make these part of the parent class.



Polymorphism

Polymorphism is the ability of a programming language to process the same instruction differently depending on its class. Where a parent and child class have a method with the same name, the method in the child class will override the method in the parent class. This means it is the method in the child class that will be performed. In the example below when we define a different __str__ method for the dog child class, this is used rather than the __str__ method defined in the parent class



Knowledge check


Questions:
Correct:

Question text


© All materials created by and copyright S.Goff