Duck Typing and Polymorphism

Learn what is polymorphism and duck typing in Ruby language.

What is polymorphism

There are some intricate definitions in object-oriented programming. However, not all programmers know what polymorphism and duck typing are, or what the difference is between the two. It happens because programming practice is often easier than theory.

The term polymorphism comes from the Greek roots poly, meaning “many”, and morphe, meaning “form”.

According to Wiktionary, polymorphism is “The ability to assume different forms or shapes” while biologically it means, “The coexistence, in the same locality, of two or more distinct forms… not connected by intermediate gradations”.That’s rather interesting, because we can see “distinct coexistence” and “not connected” simultaneously in polymorphism

The following joke can illustrate polymorphism:

Father: Son, go and get Red Label. Son: 750ml or 1 liter? Mother: Son, go and get Red Label. Son: 500 grams or 1 kg?

“Father” object assumes “Red Label” to be a whiskey, while “mother” object assumes “Red Label” to be cheese. Basically, the method (“Son”) changes based on the type of object it was called upon.

Example of polymorphism

Let’s discuss an example from programming. A commander sends a command obj.send(:sit) to different objects. A programmer would say every object has the same interface. The objects are different, but they all receive a command obj.send(:sit) sent by a commander and didn’t raise any error.

A statically-typed language programmer would define an interface for that . Here is a C# example:

interface IListener {
    void Sit();
}

class Dog : IListener {
    public void Sit() {
        // ...
    }
}

class Human : IListener {
    public void Sit() {
        // ...
    }
}

Get hands-on with 1200+ tech skills courses.