Golang | Polymorphism Using Interfaces
Last Updated :
17 Sep, 2019
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:
Example:
C
// Go program to illustrate the concept
// of polymorphism using interfaces
package main
import "fmt"
// Interface
type employee interface {
develop() int
name() string
}
// Structure 1
type team1 struct {
totalapp_1 int
name_1 string
}
// Methods of employee interface are
// implemented by the team1 structure
func (t1 team1) develop() int {
return t1.totalapp_1
}
func (t1 team1) name() string {
return t1.name_1
}
// Structure 2
type team2 struct {
totalapp_2 int
name_2 string
}
// Methods of employee interface are
// implemented by the team2 structure
func (t2 team2) develop() int {
return t2.totalapp_2
}
func (t2 team2) name() string {
return t2.name_2
}
func finaldevelop(i []employee) {
totalproject := 0
for _, ele := range i {
fmt.Printf("\nProject environment = %s\n ", ele.name())
fmt.Printf("Total number of project %d\n ", ele.develop())
totalproject += ele.develop()
}
fmt.Printf("\nTotal projects completed by "+
"the company = %d", totalproject)
}
// Main function
func main() {
res1 := team1{totalapp_1: 20,
name_1: "Android"}
res2 := team2{totalapp_2: 35,
name_2: "IOS"}
final := []employee{res1, res2}
finaldevelop(final)
}
Output:
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.
Similar Reads
Polymorphism in GoLang
Polymorphism is the ability of a message to be displayed in more than one form. Polymorphism is considered one of the important features of Object-Oriented Programming and can be achieved during either runtime or compile time. Golang is a light-object-oriented language and supports polymorphism thro
4 min read
Multiple Interfaces in Golang
In Go language, the interface is a collection of method signatures and it is also a type means you can create a variable of an interface type. In Go language, you are allowed to create multiple interfaces in your program with the help of the given syntax: type interface_name interface{ // Method sig
4 min read
Interfaces in Golang
In Go, an interface is a type that lists methods without providing their code. You canât create an instance of an interface directly, but you can make a variable of the interface type to store any value that has the needed methods.Exampletype Shape interface { Area() float64 Perimeter() float64}In t
3 min read
Object-Oriented Programming in GoLang
Object-oriented programming is a programming paradigm which uses the idea of "objects" to represent data and methods. Go does not strictly support object orientation but is a lightweight object Oriented language. Object Oriented Programming in Golang is different from that in other languages like C+
3 min read
Named Return Parameters in Golang
Prerequisite: Functions in GolangIn Golang, Named Return Parameters are generally termed as the named parameters. Golang allows giving the names to the return or result parameters of the functions in the function signature or definition. Or you can say it is the explicit naming of the return variabl
4 min read
Type Switches in GoLang
A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable. A type switch is a construct that performs multiple type assertions to determine the type of variable (rather than values) and runs the fi
3 min read
Import in GoLang
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOSÂ Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protect
9 min read
Embedding Interfaces in Golang
In Go language, the interface is a collection of method signatures and it is also a type means you can create a variable of an interface type. As we know that the Go language does not support inheritance, but the Go interface fully supports embedding. In embedding, an interface can embed other inter
6 min read
Interesting Facts About Golang
Go (also known as Golang or Go language) is the language developed by Google. Go is an open-source, statically-typed compiled, and explicit programming language. According to Google Developers, Go is a dependable and efficient programming language. Go supports Concurrent programming. Go is also a mu
2 min read
How to check pointer or interface is nil or not in Golang?
In Golang, nil check is frequently seen in GoLang code especially for error check. In most cases, nil check is straight forward, but in interface case, it's a bit different and special care needs to be taken. Here the task is to check pointer or interface is nil or not in Golang, you can check with
3 min read