C#C
C#3mo ago
Faker

Inheritance and polymorphism

Hello, can someone clarify if my understanding of inheritance and polymorphism is correct please.

From what I've understood, inheritance is a mechanism that allows one class (say dog class) to "inherit" the features of another class (say animal class for e.g). For instance, an animal may have a name, a sound which it makes and so does the dog if it inherits from animal.

I know their is something that we call dependency injection, is this an application of inheritance?

Polymorphism on the other hand means that a particular object/method can have multiple behaviours. For instance, we can have a particular method that can return an int, a double or something else depending on its method signature, this is what we refer to as method overloading.

Similarly, an object can have a general behaviour, like say we have a person, that person has a role, maybe the latter is an employee, a husband and an employee.

What polymorphism allows us to do is for each particular class of husband, employee and person, we have a general role method and the husband and employee class inherits from the person class and we can then overrides the role function for that particular class.

This is what we refer to as method overriding.
Was this page helpful?