Coding: Understanding Polymorphism
When I started learning programming in college I had no idea what I was doing, and to be honest, the teaching style was not very effective. Most of my classmates were in the same boat, we had to google a lot and work with each other to try to understand the principles of programming. After many years of coding and learning I was able to grasp the concepts. I am going to attempt to explain these principles in the simplest terms.
As mentioned in this other post [Programming Languages: Differences] one of the core principles of Object-Oriented programming is the concept of polymorphism(The concept that refers to the ability of a variable, function or object to take on multiple forms).
This concept was the most confusing to understand for me when I was learning programming. It is very similar to inheritance [Coding: Understanding Inheritance] which made it even more confusing. The difference from inheritance and polymorphism is that inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code and polymorphism is that in which we can perform a task in multiple forms or ways. It is applied to the functions or methods. Polymorphism allows the object to decide which form of the function to implement
Comparing to the example mentioned in the previous post about inheritance a Ford Mustang and Chevy Silverado would inherit properties from the vehicle class such as engine, numbers of wheels etc. In polymorphism, these two vehicles would implement their own functions/methods such as number of passengers, fuel type, color.
Microsoft has a great example of Polymorphism
public class Shape
{
// A few example members
public int X { get; private set; }
public int Y { get; private set; }
public int Height { get; set; }
public int Width { get; set; }
// Virtual method
public virtual void Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}
public class Circle : Shape
{
public override void Draw()
{
// Code to draw a circle...
Console.WriteLine("Drawing a circle");
base.Draw();
}
}
public class Rectangle : Shape
{
public override void Draw()
{
// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}
public class Triangle : Shape
{
public override void Draw()
{
// Code to draw a triangle...
Console.WriteLine("Drawing a triangle");
base.Draw();
}
}