What is Polymorphism.

Suleiman Abdullah
3 min readOct 3, 2024

--

Objective: Understand What is Polymorphism.

Lets understand polymorphism using Microsoft definition then I will try to manipulate this definition to become easy to understand.

Polymorphism(Microsoft definition) is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means “many-shaped”.

Suleiman sort of definition?

Polymorphism is the ability of an object or Instance to take many form more than its original type by inherit base class or struct or interface.

To understand this Write this couple of class and interface in the image below. Two Interface Developer, Ubisoft and two class a LeadUnityDeveloper and a JuniorUnityDeveloper Last I have created a gameManager.

Now make LeadUnityDeveloper and JuniorUnityDeveloper to Inherit from Developer and Ubisoft.

Now go to the game Manager ,create two object of Junior Unity Developer and LeadUnityDeveloper.

Now create two array of Developer and add Junior Unity Developer and LeadUnityDeveloper there.Then create another list for Ubisoft and add Junior Unity Developer and LeadUnityDeveloper.

Now you will see Junior Unity Developer and LeadUnityDevelepor take more than one form without any error. Junior can be a developer and can be Ubisoft Developer and like wise with Lead Unity Developer.

Note: This is what means to be many form means object can take more than form more than its original type.

We can use polymorphism use a single call to activate many object here, here I will loop through developers array and call the method .

Note: Not every situation need to create an object we can or loop through the object we can use .

Bonus.

Here is the last example show a ray hit object and get any component which implement Developer Interface.

Note: Make sure the Main Camera tag is set to Main Camera to avoid error.

Modification for YearsOfExperience method to change color.

Attach Junior script to game object Lead script to game object.

See you into the next one.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development