What is difference between static binding and dynamic binding

What is difference between static binding and dynamic binding

Answer :

static binding: References are resolved at compile time
dynamic binding: References are resolved at run time

Below are example:

package com.javahonk.inheritanceTest;

public class InheritanceTest {

    public static void main(String[] args) {

	String cowSounnd = "moo";
	String elephantSounnd = "trumpet";

	//Object instance will be resolved at run time
	if (getAnimalSound(cowSounnd) instanceof Cow) {
	    System.out.println("It's cow");
	}

	//Object instance will be resolved at run time
	if (getAnimalSound(elephantSounnd) instanceof Elephant) {
	    System.out.println("It's elephant");
	}
    }

    private static Animal getAnimalSound(String sound) {

	if (sound.equalsIgnoreCase("moo")) {
	    return new Cow();
	} else {
	    return new Elephant();
	}

    }

}

 

Output:

It's cow
It's elephant

 

Leave a Reply

Your email address will not be published. Required fields are marked *