If you understand the concept of inheritance and polymorphism, I know that your code is always clean, simple, and optimized to fulfill its function efficiently. If you don’t understand it yet, don’t worry, I’ll tell you what it’s about so you can simplify your work.
Technically speaking, polymorphism is the capacity that some languages have, that allows them to send syntactically the same messages to objects of different types (but with the same inheritance) and that each one responds in its own way.
Therefore, as its name says and as we can deduce from the small definition that I have given you in the previous paragraph, polymorphism starts from the idea that a method has many forms and that it responds accurately depending on what class it belongs to.
For example, in a video game, we can have an object called a character, and it can have different classes such as warrior and magician, which respond to the same method called attack. However, as we have said that they must respond correctly depending on their class, the polymorphism would ensure that the warrior’s attack is, for example, with a sword and that of the magician with a book and a spell, thus being the character, a polymorphic object.
In summary, it is a mechanism that allows the same method to be different depending on the class that is using it and avoids the creation of a different function for each class.
In short, Polymorphism consists of redefining a method of a parent class in a child class, in this way, the key utility of polymorphism is to reduce the maintenance of computer programs to the maximum, through a great advantage, which is to create new types without the need to alter those that we have already done previously.
It is a compile-time method. It means that there are several methods present in a class but with the same name although different types, orders, or numbers of parameters, that is, independent of each other. In other words, overloading is defining a new method the same as an old one, but changing the type or number of parameters, thus using it for the same function but with different behavior.
It happens at runtime using the same method, therefore, unlike overloading, it uses the same signature, in two classes that share the same inheritance and connect through it. In this case, the parameter must be the same and is used when a different function must be done.
Remember that all the concepts related to software development are better understood when they are put into practice, you have the theory now it’s up to you to sit down and start applying it in your own projects.
Based on your experience, how would you simply define polymorphism?
I read you in the comments.
Remember that you can also join the conversation through my social networks, you can find me on Twitter as @BarnuevoLeo and find me on LinkedIn as Leo J. Barnuevo.
Source: DEV Community