Spaces:
Running
Running
| Often, when programming an object, you come across a situation where 2 classes have COMMON FEATURES. | |
| An example could be the classes Teacher and Student. | |
| Both classes would have at least the attributes name and email. | |
| However, in addition to the common attributes, | |
| the classes would also have separate attributes: | |
| for example, a teacher would not have an attribute for the number of credits, and | |
| a student would not have an attribute for the course being taught. | |
| It is of course possible to create 2 separate classes with similar attributes. | |
| However, it would often make more sense to use class hierarchies in such a situation. | |
| The idea of a class hierarchy is that classes can have DESCENDANTS and corresponding PARENTS (or "ancestors"). | |
| A class inherits characteristics from its parent. | |
| If a class has multiple children, they all share certain common characteristics. | |
| In addition to these, the children may, of course, have their own characteristics that are different from one another. | |
| In addition to the client-supplier relationship discussed earlier, | |
| the inheritance relationship is another important relationship in object oriented programming | |
| Parent and child classes | |
| If class A inherits class B, | |
| class A is said to be a child class of B. | |
| Similarly, B is the parent class of A. | |
| The following figure illustrates the inheritance relationships: | |
|  | |
| In the picture, for example | |
| - A Vehicle is a superclass of the categories Car and Motorcycle | |
| - The classes Hatchback and Truck are subclasses of the class Car | |
| - All other classes inherit the properties of the 'Vehicle' classes: | |
| for example, Car and Motorcycle are both vehicles, but they also have their own, different properties. | |
| The inheritance relationship therefore means that the inheriting class is also a parent class. | |
| For example, a hatchback is also a car and a vehicle. | |
| Thus, the class Dog could naturally inherit the class Animal, | |
| but the class Cat could not inherit the class Dog (because a dog is an animal, but a cat is not a dog). | |
| Similarly, the class Paperback could inherit the class Book, | |
| but the class Page could not (paperback is a book, page is not a book, even though a book has pages). | |