Demystifying The Discombobulating Concept Of Polymorphism

Among the 3 core concepts of Object-Oriented Programming, Polymorphism really stands out as the most discombobulating one. So confusing that when your professor mentions it, you will rapidly look around the classroom just to confirm that you are not in a religion class wherein the professor is introducing a new badass religion. Then, as Mr. I-will-intimidate-you-with-words-that-will-make-your-nose-bleed continues to talk about this thing, you will realize that it is another mindfuck in Computer Science. And you will instantly discover your true calling — “f*ck this sh*t! I will be a stripper!”.

But before you decide to do some horrifying striptease wearing your treasured bacon briefs, let me tell you that Polymorphism just pertains to the ability to take many forms. Poly means many and Morph means to take another form.That’s just it! So put those clothes back!

Polymorphic grandpa

Object-Oriented Programming

All of us, if not, almost 99.9% of us heard this Polymorphism-thingy when we studied Object-Oriented Programming, together with the other pillars of OOP: Encapsulation and Inheritance. So with that fact, virtually all examples of Polymorphism out there are presented in an OOP way, which in that case may look something like this:

public abstract class Human
{
  public abstract void goPee();
}


public class Male extends Human
{
  public void goPee(){
    System.out.println("Stand Up");
  }
}


public class Female extends Human
{
  public void goPee(){
    System.out.println("Sit Down");
  }
}

Given that set of classes, you can do something like this:

Human gary = new Male();
Human sandy = new Female();

gary.goPee();  // "Stand Up"
sandy.goPee(); // "Sit Down"

Let’s not dive into Java’s technicality, let’s just say that Human is just an abstract concept here. You cannot create something that is just a Human, it must be either a Male or a Female. So you cannot do something like:

Human anonymous = new Human();

It’s like creating a Human without a genital.

must fight imagination…

This kind of Polymorphism is what all of us pertain when we talk about this sh*t, and this is called Subtype Polymorphism — An object of class Human, can take any of its subclass forms: Male or Female.

Method Overriding

Confession time baby. In OOP, Polymorphism is not simply about an object taking many forms, but in doing so it also needs to maintain its interface.

What?

Human class provides a goPee method for its subclasses, but it doesn’t have a body, because again it doesn’t know how to pee! So its subclasses are tasked to override, or you can just say overwrite, Human’s goPee method with their own version.

The magic here is that you don’t need to explicitly say which goPee version you are pertaining to when you instruct gary and sandy. You don’t need to say, “Hey Gary, when I tell you to pee you must stand up.”. You don’t need to tell that to any Male you know bro! They already know it by heart. They will automatically know what goPee version to execute depending on their type. So you can always be confident that an object will use the right method version no matter what happen.

for (int i=0; i < 100; i++){
  Human person = createRandomHuman();  // create either a Male or Female
  person.goPee();   // will always do the right thing
}

Method Overriding provides you a way to maintain the same interface (same method) but with a different form or implementation. This is very useful because you don't need to change the way you interact with the object when it changes its type.

See this example without Method Overriding:

class Male extends Human 
{
  // We are still required to override this
  // because it's f*cking Java's rule. But we
  // will not use this!
  public void goPee(){}

  // Instead we will use this
  public void goPeeLikeAMan(){
    System.out.println("Stand Up");
  }
}

class Female extends Human
{
  public void goPee(){}

  public void goPeeLikeAWoman(){
    System.out.println("Sit Down");
  }
}

for (int i=0; i < 100; i++){
  Human person = createRandomHuman();
  
  if (person instanceof Male){
    // We typecast person because we need 
    // to tell that it is a Male, so it can
    // use the Male specific method goPeeLikeAMan()
    ((Male)person).goPeeLikeAMan();
  }
  else {
    ((Female)person).goPeeLikeAWoman();
  }
}

Without method overriding, you are required to manually choose the right method to use depending on the object's type. We are obliged to do an If-else statement so that person can use the right method. It seems that it is not a big burden to do an If-else statement and a little typecasting right?

NO! Imagine you have a thousand lines in your code that uses that kind logic --- Good luck!

More on Method Overriding

Now, we'll create a Female subclass.

class Female extends Human
{
  public void goPee(){
    System.out.println("Sit Down");
  }
}

class JapaneseGirl extends Female {} 


Female shuzuka = new JapaneseGirl();
shuzuka.goPee(); // "Sit Down"

Okay. Since JapaneseGirl is a type of Female, when we politely asked shuzuka to take a pee, she sat down --- Basic Inheritance.

But then, she is not just an ordinary female, she is a JAPANESE GIRL!! Shuzuka needs to do something crazy!

class JapaneseGirl extends Female 
{
  public void goPee(){
    System.out.println("Jump"); // Da Fuq?
  }  
}

Female shuzuka = new JapaneseGirl();
shuzuka.goPee(); // "Jump"

Now that's more Japanese. Method overriding is achieved by declaring a method within a subclass with the same method signature (name and parameter) as the original method found in the parent class. It is like ignoring the method that your parent provides you and creating your own version. It's a way of saying something like, "Sitting while peeing is so mainstream, and I'm a Japanese! So I will jump!"

(In moments like this, lack of imagination becomes advantageous.)

Polymorphism in Functional Programming?

Back in my horrible college days, I had this awkward argument with my professor about Polymorphism. It's during our Programming Language class, I can't remember what ignites the issue but he asked about what Polymorphism is. Nobody seems to know the answer that time, so I confidently raised my hand and wrote something like this on the board:

class Dog extends Animal {}
class Cat extends Animal {}

Animal pet = new Dog();

He was speechless for a moment. He looked very puzzled so I looked at the whiteboard again just to check that I didn't write in Assembly. Then she, oh sorry, he approached the board and uncertainly wrote something like this:

int foo(){}
int foo(int){}
int foo(int, int){}
int foo(int, int, ...){}

I stuttered and said, "Bbbbbbut that is function overloading". The whole class agreed to my point. But the professor insisted that it was Polymorphism. A couple of arguments were raised before the mayhem ended with both parties baffled.

It turned out that function or method overloading is a technique used for Polymorphism. Despite the stereotype of Polymorphism being an Object-Oriented concept only.

int add(int a, int b)
{
  return a + b;
}

int add(int a, int b, int c)
{
  return a + b + c;
}

add(1, 2, 3);  // 6
add(250, 250); // 500

Method overloading, also called Ad-Hoc Polymorphism, can be achieved by declaring a method with the same name, but with different parameter types or parameter count. With the code provided, the correct add method will be magically called depending on the parameters that you passed. It is still considered Polymorphism because, with respect to the simplest definition of Polymorphism, the add method can take many forms. Awyeah!

Conclusion

Polymorphism pertains to the ability to take many forms. It is popularly associated with Object-Oriented Programming known as Subtype Polymorphism, but it is also present on Functional Programming via Method Overloading. Method Overriding is used with Subtype Polymorphism to call the right method depending on the object's type, and more importantly to feel the true orgasmic power of Polymorphism in OOP.

my mind is full of f*ck

Lastly, I therefore f*cking conclude that Japanese women are weird.

>

4 Comments

  • March 25, 2012 - 1:21 am | Permalink

    Great explanation! Easy to understand. Link ko to sa blog ko. Ok lang?

    “awkward argument with my professor about Polymorphism. It’s during our Programming Language class” Naalala ko to ngtaka rin ako nung ginawa nya ung overloading. I think ang problema back then was tinuro lang satin ang definition ng Polymorphism pero hindi natin talaga ginamit or naintindihan ang paggamit. Parang my ilang lab problems lang tayo on method overloading in C tapos un na un. In terms of school subjects, sa software engineering class mas maiintindihan ung concept kasi makikita mo na ung actual use.

    • Karl Paragua
      March 26, 2012 - 10:49 am | Permalink

      Thanks fre. Sige lang. link mo lang sa blog mo. :) Thanks

      I think, there are few professors that give importance to polymorphism, at least in our university. I don’t know the reason behind that. But I think this one is one of the most overrated concept in Computer Science, it sounds intimidating but the reality is, it is somewhat simple.

  • April 19, 2012 - 3:54 pm | Permalink

    hey there. nice post. :D
    very informative and nakakatuwa.. I think mas naiintindihan ko na ngayon ang polymorphism because of this post XD
    can i add you to my blog list, as well? XD

    • Karl Paragua
      April 19, 2012 - 3:58 pm | Permalink

      hey. Thank you! :)
      Yes, you can add me on your blog list. It’s my pleasure.

  • Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.