Is all dynamic binding a kind of polymorphism?

1.7k views Asked by At

Is all dynamic binding considered to be polymorphism? Specifically, I'm talking about Java. If not, please explain both terms.

What I know: not all inheritance is polymorphism but inheritance is used in all polymorphism.

2

There are 2 answers

2
Jack On BEST ANSWER

First of all dynamic binding (or late binding) is an improper term. You are talking about dynamic dispatch which is a different thing.

Dynamic binding is choosing which implementation of a method will be called at runtime, but this doesn't happen in Java. But you have dynamic dispatch which is the ability to choose the correct polymorphic implementation of a method at compile time (which usually translates to choosing the most specialized version of the method/function).

But I wouldn't say that dynamic dispatch is polymorphism, I'd say that to support polymorphism you need a mechanism to choose the correct implementation of a method and this is dynamic dispatch.

Inheritance is a kind of polymorphism called subtyping (or subtype polymorphism) so, contrary to what you say, inheritance is always a form of polymorphism, but other kinds of polymorphism exist, think about:

  • ad hoc polymorphism (implemented through overloading) where the same function has different meanings when applied to different arguments
  • parametric polymorphism (implemented with Generics in Java) where you have types with type variables so that a single type can express infinite number of types by binding the variable to a specific type (or a class of types), think about List<Integer>
0
Vyshakh Babji On

If the method call is decided at runtime- it is dynamic polymorphism. If the method call is decided by compiler during compile time it is called static polymorphism.

Example:

public static void eat (Veg vegetable) {
    System.out.println("I am vegetarian");
}
public static void eat(Meat meat) {
    System.out.println("I am non-vegetarian");
}

//if your main is this way
public static void main(String args[])
{
    Veg v = new Meat();
    callEat(v);
}

It prints "I am vegetarian" . This is decided by compiler on runtime. Its also called as method overriding.

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

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

void main (){
   add(1,2);
   add(1,2,3);
}

Here the function is choosen depending on the parameter passed even when the name and return type of the method is the same. This is done at compile time. This is static polymorphism. It is also called as method overriding.