I would like to know the advantage of Dynamic Binding in java.
public class Animal {
public String type = "mammal";
public void show() {
System.out.println("The animal is a: " + type);
}
}
public class Dog extends Animal {
public String type;
public Dog(String type){
this.type = type;
}
public void show() {
System.out.println("The dog is a: " + type);
}
}
public static void main(String[] args) {
Animal doggie = new Dog("daschund");
doggie.show(); // "The dog is a: daschund" (dynamic binding)
System.out.println("The type is: " + doggie.type); //"The type is: mammal" (static binding)
}
I think, it is a Inheritance strategies. But some people call like Dynamic Binding. That’s why, I assume what will be strange in it.
The benefit of it is that your behaviour is bound to the type of the object that you invoke it on, without you knowing what precise type it actually is. e.g. if you’re passed an Animal, you don’t know whether it’s a Cat/Dog/whatever, but it’ll adopt the appropriate behaviour regardless.
e.g.
The above will bark, miaow, bleet etc. appropriately for each animal in the above collection.
I can pass you something and providing it adheres to the required Animal interface, your code will continue to work if/when I introduce a new animal at a later stage. Your code doesn’t need to know the mechanics of how a
Dogbarks – just that you instruct that behaviour through the appropriate method.Note: I think your example above would be clearer by making
Animalan abstract class. That way your behaviour will largely come from the derived concrete classes.