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.
6 Replies
I know their is something that we call dependency injection, is this an application of inheritance?No, those are unrelated concepts.
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.Method overloading and polymorphism are different things.
ah ? I think I'm confused about interfaces and inheritance?
Method overloading and polymorphism are different things.I thought method overloading was an application of polymorphism?
method overriding not method overloading
inheritance is about reusing code between classes, polymorphism is about using the same method in different ways, and dependency injection is a separate pattern for decoupling not inheritance
but there is compile time polymorphism and runtime polymorphism no?
you are right
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
since the word "polymorphism" itself is also polymorphism
Polymorphism (computer science)
In programming language theory and type theory, polymorphism is the approach that allows a value type to assume different types.
In object-oriented programming, polymorphism is the provision of one interface to entities of different data types. The concept is borrowed from a principle in biology where an organism or species can have many differ...