Dynamic bond

from Wikipedia, the free encyclopedia

In computer science , especially to the object-oriented programming , which is dynamic binding ( English dynamic binding / dynamic dispatch ) a term that the handling of the compiler with polymorphic describes methods.

Dynamic binding is used when a method call is resolved at runtime based on the actual (dynamic) type of an object.

Explanation

In the case of class hierarchies, a variable whose type is set to a certain class can also contain instances of its subclasses in which methods of the superclass may have been overwritten.

If you now call a certain method for the object stored in the variable, there are two candidates:

  1. The method of the upper class
  2. The redefined method of the subclass

Dynamic binding is used when, in such cases, the respective version of the method is called at runtime depending on whether the object is an instance of the superclass or a subclass. If the method of the superclass is always used instead, one speaks of static binding. Many object-oriented programming languages ​​allow you to define individually for each method whether static or dynamic binding is to be used. This property is also inherited.

Dynamic binding is of enormous importance for object-oriented programming, since the flexibility of inheritance only comes into play through dynamic binding.

implementation

Dynamic binding can be implemented in two different ways.

Virtual Method Table

For each type with virtual methods, the compiler creates a table of virtual methods that contains references to the methods to be called.

Dispatch Tree

Each time a dynamic method is called , the compiler inserts a branch that selects the correct method based on the object type.

example

A typical example of dynamic binding in Java :

import java.util.*;

class Saeugetier {
    void steckbrief() {
        System.out.println("Ich bin ein Säugetier.");
    }
}

class Gepard extends Saeugetier {
    void steckbrief() {
        System.out.println("Ich bin ein Gepard.");
    }
}

class Elefant extends Saeugetier {
    void steckbrief() {
        System.out.println("Ich bin ein Elefant.");
    }
}

public class DynamischeBindungBeispiel {
    public static void main(String[] args) {
        List<Saeugetier> tiere = new ArrayList<Saeugetier>();
        tiere.add(new Saeugetier());
        tiere.add(new Gepard());
        tiere.add(new Elefant());

        for (Saeugetier tier: tiere) {
            tier.steckbrief();
        }
    }
}

output

Ich bin ein Säugetier.
Ich bin ein Gepard.
Ich bin ein Elefant.