40

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!

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
gerky
  • 6,267
  • 11
  • 55
  • 82

4 Answers4

40

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).

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • in java you can use some kind of duck typing using interfaces. – some_coder Jul 16 '12 at 11:08
  • also... with polymorphism you can alter the behavior of an childclass. – some_coder Jul 16 '12 at 11:09
  • 14
    "Polymorphism means a subclass can override a method of the base class." - isn't this just inheritance? – gerky Jul 16 '12 at 13:00
  • 3
    @mumble: In object-oriented programming it's indeed done with inheritance. But polymorphism can also be done without classes, such as defining a function `add(int x, int y)` and a function `add(String s, String t)` which have the same name but the actual arguments determine which function is actually called. – Simeon Visser Jul 16 '12 at 13:05
  • 2
    if it is polymorphism you are saying, then what is overriding ? – Rupesh Patel Jul 16 '12 at 13:05
  • @RupeshPatel: My definition is related to object-oriented programming. You could say that overriding a method creates polymorphism in object-oriented programming languages. – Simeon Visser Jul 16 '12 at 13:08
  • ohh..right, sometimes I forget to think outside oop, thanks for clarifying that issue about overriding vs polymorphism as well. I also found this useful, a very nice explanation regarding polymorphism for java, http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading – gerky Jul 16 '12 at 18:40
  • @SimeonVisser : Ok agreed but as I guess, the word "poly" stands for multiple usage of same function name, in oop overriding doesn't meet it. You can not do different things by passing different parameters So it is not polymorphism but simply overriding. Both are totally different things. Please En lite me. – Rupesh Patel Jul 17 '12 at 13:29
  • @RupeshPatel: Polymorphism in OOP is not done by passing different parameters but by allowing the same method to do different things in subclasses. In other words, the "poly" means the same method can have multiple implementations in different classes. – Simeon Visser Jul 17 '12 at 13:40
  • @SimeonVisser So you are saying that overloading(Polymorphism ) and overriding is the same thing ???? !!!!! It is nothing spacial with OOP case. Can you prove this ???? Let me put my understandings – Rupesh Patel Jul 18 '12 at 08:40
  • @SimeonVisser 1. In overloading,there is a relation ship between methods available in the same class where as in overriding,there is relationship between a super class method and subclass method. 2. overloading doesn't block inheritence from the superclass where as overridding blocks inheritence. 3. in overloading,seperate methods share the same name where as in overridding,subclass methods replaces the superclass. 4.overloading must have different method signatures where as overriding must have same signature. – Rupesh Patel Jul 18 '12 at 08:40
  • @RupeshPatel : Overloading and overriding are not the same as you have explained. However, they are both examples of polymorphism in a programming language. – Simeon Visser Jul 18 '12 at 09:24
  • @SimeonVisser ok got it! Thanks :) This is helpful. Can you please edit and extend the definition, So people like me are not dis-guided. Thanks you very much for replies. – Rupesh Patel Jul 18 '12 at 09:28
  • Either polymorphism or duck-typing could be implemented in terms of the other if every class wanted member `Foo` to be available for duck-typing also implemented interface `IFoo`, and if every class which wanted to expose a polymorphic set of methods had a member with a known name that would return a wrapper that implements those methods. – supercat Jun 16 '13 at 21:45
  • Interesting points. Kinda late to the party but. Overloading + Inheritance + Overriding all facilitate in the polymorphic behavior of subclasses. (note: Poly=many, morph=forms). Now lets step back on implementation detail, polymorphic subclasses might act/behave differently. Duck Typing on the other hand is all about using properties or methods of a given instance/object without caring about what is the type of the object. In Python, `StringIO` is more/less duck typed to behave like a file object and the code that expect a file object should just carry on without any issues. – dopstar Nov 20 '15 at 22:00
  • Polymorphism is Duck and Platypus both overriding the OpenBill/CloseBill methods from the DuckedAnimal class they inherit. Duck typing is dropping in a Platypus and having it work because it has a bill, even though it may not implement Quack. – Jared Mar 25 '18 at 15:46
  • This is simply wrong. Duck typing is a form of dynamic polymorphism (see, e.g. https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Static_and_dynamic_polymorphism ). You do not need to inherit and override to have polymorphic behavior. – Patrick Maupin Apr 26 '23 at 23:23
21

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.
S.B
  • 13,077
  • 10
  • 22
  • 49
Prakash D
  • 403
  • 4
  • 6
  • 5
    The first case to me seems like simple inheritance. I really don't think it makes sense to talk about polymorphism in a dynamically typed language like Python. Essentially the first case here is also duck typing. In Python function arguments don't have types, so you can pass anything to any function. That's not polymorphism. It's just dynamic typing. – Evan Zamir Jan 06 '17 at 19:02
  • 2
    In first one, it's more than simple inheritance, right? There's an array of animals, and he's calling talk() on its elements. That's subtype polymorphism right there. Objective of simple inheritance is basically just code sharing between classes. This clearly goes beyond that. – Hashman Jun 12 '17 at 19:35
  • 1
    This is the best example – avibrazil Aug 01 '20 at 08:44
16

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.

Andy
  • 1,452
  • 1
  • 13
  • 18
2

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 
JDB
  • 25,172
  • 5
  • 72
  • 123
Prasad KM
  • 31
  • 1