Polymorphism by definition means many forms. Which signifies, a variable can exist in different forms.
An Animal can exist in different forms. They are Dog, Cat, Deer e.t.c. So an Animal is not a physical entity but Cat, Dog e.t.c are.
Now, just think about the sound() behaviour? All Animals makes some kind of sound. But they don't make the same sound.
Cats makes a 'meao' sound whereas Dogs bark.
So, the sound() behaviour would change based on the Animals.
And to implement this, Interface would be a best fit.
All we need to do is define an Interface named Animal. Which would only have the 'sound()' behaviour.
And there would be two Structures Cat and Dog. And both will be binded to the Interface Animal.
So, let's implement in the next example.
package main import "fmt" type Animal interface { sound() } type Cat struct { noise string } type Dog struct { noise string } func (a Cat) sound() { fmt.Println("Cats",a.noise) } func (a Dog) sound() { fmt.Println("Dogs",a.noise) } func main() { var animalCat Animal animalCat = Cat{noise:"Meao" } animalCat.sound() var animalDog Animal animalDog = Dog{noise:"Bark" } animalDog.sound() }
So as said, in the above code, we have declared the 'Animal' Interface that just has the sound() Function.
type Animal interface { sound() }
Then we have declared the 'Cat' and 'Dog' Structure that has an attribute called 'noise'(i.e. 'meao' for Cat and 'bark' for Dog).
type Cat struct { noise string } type Dog struct { noise string }
And declared 'sound()' Function for both the Structures, 'Cat' and 'Dog'.
func (a Cat) sound() { fmt.Println("Cats",a.noise) } func (a Dog) sound() { fmt.Println("Dogs",a.noise) }
Now since, the 'sound()' method is present for both the Structures, 'Cat' and 'Dog'. Both 'Cat' and 'Dog' is tied to the Interface 'Animal'.
Now, it's time for us to create the Interface 'Animal' type variable(i.e. 'animalCat'),
And assign 'Cat' type variable to the Interface type variable 'animalCat'.
And when we call the sound() method from Interface type variable 'animalCat'.
The 'sound()' Function of Cat structure gets called.
func (a Cat) sound() { fmt.Println("Cats",a.noise) }
And we get the below output,
Similarly, for 'Dog' structure, we have followed the same rule,
var animalDog Animal animalDog = Dog{noise:"Bark" } animalDog.sound()
And the 'sound()' Function of 'Dog' gets called,
func (a Dog) sound() { fmt.Println("Dogs",a.noise) }
Printing the below output,
You have created an Interface of type Animal and initialised with Cat type.
Also you have created an Interface of type Animal and initialised with Dog type.
Even though the variable is of type 'Interface Animal', the correct Function of 'Cat' and 'Dog' gets called.
This is Polymorphism.