Golang | Polymorphism Using Interfaces
The word polymorphism means having many forms. Or in other words, we can define polymorphism as the ability of a message to be displayed in more than one form. Or in technical term polymorphism means same method name (but different signatures) being uses for different types. For example, a woman at the same time can have different characteristic. Like a mother, a wife, a sister, an employee, etc. So the same person posses different behavior in different situations. This is called polymorphism.
In Go language, we cannot achieve polymorphism with the help of classes because Go language does not support classes but can achieve by using interfaces. As we already know that the interfaces are implicitly implemented in Go. So, when we create an interface and other types want to implement that interface, then those types use that interface with the help of the methods defined in the interface without knowing the type. In an interface, a variable of an interface type can contain any value which implements the interface. This property helps interfaces to achieve polymorphism in the Go language. Let us discuss with the help of an example:
Project environment = Android Total number of project 20 Project environment = IOS Total number of project 35 Total projects completed by the company = 55
Explanation: In the above example, we have an interface name as an employee. This interface contains two methods, i.e, develop() and name() method, here, develop() method returns the total number of projects and name() method return the name of the environment in which they are developed.
Now we have two structures, i.e, team1, and team2. Both the structures contain two-two fields, i.e, totalapp_1 int, name_1 string, totalapp_2 int, and name_2 string. Now, these structures (i.e, team1 and team2) are implementing the methods of the employee interface.
After that, we create a function named as finaldevelop() which returns the total number of projects developed by the company. It accepts a slice of employee interfaces as an argument and calculates the total number of the projects developed by the company by iterating over the slice and call develop() method on each of its elements. It also displays the environment of the project by calling the name() method. According to the concrete type of the employee interface, different develop() and name() methods will be called. So, we achieved polymorphism in the finaldevelop() function.
If you add another team in this program which implements employee interface this finaldevelop() function will calculate the total number of the projects developed by the company without any change due to polymorphism.