Saturday, January 26, 2019

Polymorphism and Duck Typing

Polymorphism is just a fancy way of saying that we can use an inherited class in place of a base class. This is a very important concept in typed languages, but is automatically handled for you in dynamically typed languages like JavaScipt. One of the nicest features of JavaScipt is that you not only can use a child class in place of a parent class, but you can use any class that has the methods and properties that you want to use. This is known as duck typing and is called that from the saying "if it looks like a duck, walks like a duck, and quacks like a duck then it is probably a duck."

The power of polymorphism comes from the ability to call a function that takes a base class with any class that is inherited from that class. For example, lets say we create a function for playing with the pets that we created last section.
// Note - See previous section for the Pet classes 

// function for pet class objects
function playWithPet(pet) {
printTestLine("Playing with " +;

// Pet polymorphism test code
printTestLine("Class polymorphism using inherited pets:");
var cat = new Cat("Abby")
var dog = new Dog("Smokie")
var fish = new Pet("Dora", "Fish")


Notice that we can call this function with any of the pet classes that we created. This is a very important concept as it means that we can create functions that use base classes and they will continue to work with classes that we create in the future giving us a lot of flexibility. Duck typing takes this a bit further by not even requiring the same base type. Lets test this by creating a non-pet duck class.

Duck = function(name) { = name;

this.makeNoise = function() {
printTestLine( + " Quacks!");

// Testing duck-typing
printTestLine("Duck-typing test:");
var duck = new Duck("Daffy");

As you can see, the only requirement JavaScript has is that the method being called exists. The Duck class did not need to inherit from the pet class nor did it need to implement all the methods in the pet class, just the methods and properties that any function it was being called with requires.

For smaller programs, duck-typing is a very handy feature, but it can result in problems with larger projects. This is why interfaces are often used in place of duck-typing in languages like Java.

No comments: