35
votes

I'm a little confused with the two terms, here's what I know:

Polymorphism is the ability of object of different types to be handled by a common interface. While duck typing, is a kind of dynamic typing that allows objects of different types to respond to the same methods.

From what I understand, polymorphism is more about creating an interface that can be shared across different classes. And duck typing is about loose typing that will allow methods to be called as long as it is found on the receiver of the message.

Is this correct? I'm pretty confused on the two, they seem related but I do not know what their relationship is. Thanks a lot in advance!

4

4 Answers

35
votes

Polymorphism (in the context of object-oriented programming) means a subclass can override a method of the base class. This means a method of a class can do different things in subclasses. For example: a class Animal can have a method talk() and the subclasses Dog and Cat of Animal can let the method talk() make different sounds.

Duck typing means code will simply accept any object that has a particular method. Let's say we have the following code: animal.quack(). If the given object animal has the method we want to call then we're good (no additional type requirements needed). It does not matter whether animal is actually a Duck or a different animal which also happens to quack. That's why it is called duck typing: if it looks like a duck (e.g., it has a method called quack() then we can act as if that object is a duck).

So are these related? They are simply separate features that a programming language may have. There are programming languages which have polymorphism but that do not have duck typing (such as Java). There are also languages that have polymorphism and duck typing (such as Python).

17
votes

This is an example for Polymorphism in Python.

class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return 'Meow!'

class Dog(Animal):
    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),
           Cat('Mr. Mistoffelees'),
           Dog('Lassie')]

for animal in animals:
    print animal
    print animal.name + ': ' + animal.talk()

This is an example for duck Typing in Python.

class Duck:
    def quack(self):
        print("Quaaaaaack!")
    def feathers(self):
        print("The duck has white and gray feathers.")
    def name(self):
        print("ITS A DUCK NO NAME")


class Person:
    def quack(self):
        print("The person imitates a duck.")
    def feathers(self):
        print("The person takes a feather from the ground and shows it.")
    def name(self):
        print("John Smith")

def in_the_forest(duck):
    duck.quack()
    duck.feathers()
    duck.name()

def game():
    for element in [ Duck() , Person()]:
        in_the_forest(element)

game()
  • In polymorphism we see subclass (Cat and Dog) inheriting from the parent class (Animal) and overriding the method Talk.
  • In case of duck typing we don’t create a subclass instead new class is created with method having same name but different function.
15
votes

Short Answer:

Duck typing is one way of achieving Polymorphism. Another way is by using static typing.

Long Answer:

There are two different concepts involved here, typing and programming technique.

Duck typing is a type of typing. And typing means when to throw error when an object passed around isn't what is expected. Duck typing is a kind of typing where it throws error when the program is running and the method being called isn't available. Static typing comes with compile time checking, so if the type info doesn't match, it will throw error when you compile the code. And that is typing.

Polymorphism is a programming technique where you allow multiple types of object to fulfill certain responsibilities. You can do that by using a base type to represent all the child class types. You can use duck typing to represent all the different types that have the needed methods. You can use an interface to represent all the types that implement the interface.

There are answers saying polymorphism is inheritance, and that is not correct. Although you can use inheritance to create polymorphic behavior and usually that's what you do, but that's not what polymorphism is about.

For one, you don't need inheritance to have polymorphism as described above.

Secondly, the term "Polymorphism" is more meaningful in the context of the client code that depends on abstraction, and not the implementation code. Just because you have a super class and a few other classes that inherit from it and overriding some methods does not mean it's polymorphism, to create polymorphism you have to write client code in a polymorphic way to consume these classes.

2
votes

Two type Polymorphism

  1. Method overloading(Compile time Polymorphism ).
  2. Method overriding(Run Time Polymorphism ).

Method overloading :- same function name and different data type is known as Method overloading

Example :

  int addTwovalues(int a, int b)
  { return (a+b)}

  float addTwovalues(float a, float b)
  { return (a+b)}

  Method overriding :- same function name and same data type but different Class
     is known as       Method overriding.


  class a
 {
  virtual int addtwovalues()
   {  // to do  }
  }
 class b:a
 {
     override int addtwovalues()
   {  // to do  }

  }



  a obj=new a();
  obj.addtwovalues();

  b objb=new a();
  objb.addtwovalues();  //run time Polymorphism