Static Binding and Dynamic Binding
Asked Answered
J

6

32

I am really confused about dynamic binding and static binding. I have read that determining the type of an object at compile time is called static binding and determining it at runtime is called dynamic binding.

What happens in the code below:

Static binding or dynamic binding?
What kind of polymorphism does this show?

class Animal
{
    void eat()
    {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal
{
    void eat()
    {
        System.out.println("Dog is eating");
    }
}

public static void main(String args[])
{
    Animal a=new Animal();
    a.eat();
}
Josselyn answered 20/5, 2013 at 10:33 Comment(3)
shouldn't your a.eat() be inside the main method?Erle
Read "Head first core java" ASAP.Steamtight
this is more of dynamic bindingUndertrump
S
69

Your example is dynamic binding, because at run time it is determined what the type of a is, and the appropriate method is called.

Now assume you have the following two methods as well:

public static void callEat(Animal animal) {
    System.out.println("Animal is eating");
}
public static void callEat(Dog dog) {
    System.out.println("Dog is eating");
}

Even if you change your main to

public static void main(String args[])
{
    Animal a = new Dog();
    callEat(a);
}

this will print Animal is eating, because the call to callEat uses static binding, and the compiler only knows that a is of type Animal.

Supinate answered 20/5, 2013 at 10:57 Comment(4)
@Heuster Thanx for such a wonderful example. But can u tell me what kind of polymorphism my code is exhibiting? static or runtime polymorphism?Josselyn
hummm, well you didn't specify that it really rely on override/overload. but great answer :-)Pulmotor
@user2401175 as Muhammad Ramahy just mentioned: you override the method eat of class Animal. This uses dynamic binding. In my second example, I overload the method callEat with multiple signatures. This uses static binding.Supinate
@VincentvanderWeele So does it mean that if there is method overloading, it will be always static binding and if there is method overriding then binding will be dynamic?Guesthouse
P
23

This really depends on overloading and overriding if you did something like this:

public class Animal{}


public class Dog extends Animal{}

public class AnimalActivity{

    public void eat(Animal a){
        System.out.println("Animal is eating");
    }

    public void eat(Dog d){
        System.out.println("Dog is eating");
    }
}

then in the main class:

public static void main(String args[])
{
    Animal a=new Animal();
    Animal d=new Dog();
    AnimalActivity aa=new AnimalActivity();
    aa.eat(a);
    aa.eat(d);
}

the result in the two cases will be: Animal is eating

but lets twist it some, lets have this:

public class Animal{
    public void eat(){
        System.out.println("Animal is eating");
    }
}

then:

public class Dog extends Animal{
    public void eat(){
        System.out.println("Dog is eating");
    }
}

then in the main class:

public static void main(String args[]){
    Animal d=new Dog();
    Animal a=new Animal();
    a.eat();
    d.eat();
}

now the result should be:

Animal is eating
Dog is eating

this is because overloading binds at compile time "static binding" while overriding binds at run time "dynamic binding"

Pulmotor answered 20/5, 2013 at 11:46 Comment(0)
C
1

Your current code will output Animal is eating

However, in your main class, if you created an object of type Dog and assigned it to Animal, then your output will be Dog is eating due to dynamic binding.

public static void main(String args[])
{
    Animal a = new Dog(); // An object of Dog is assigned to Animal
    a.eat(); // Dynamically determines which eat() method to call
}

Even though a is declared as Animal it is pointing to an object of type Dog. So, at runtime, the object type is determined and appropriate eat() method is called.

One way to think of it is, method overloading is statically bound and method overriding is dynamically bound.

Chromogen answered 20/5, 2013 at 10:42 Comment(3)
So,u r saying that my code is exhibiting static binding,rite?Josselyn
@user2401175 no. The answer says "due to dynamic binding". So the code shows an example of dynamic binding, because the eat() method is being chosen at runtime, based on the concrete type of the animal on which it's called (Dog), and not of the declared type of the variable (Animal).Sapid
@srikanta: your comment contradicts your answer. The OP's code is the same as yours. The eat() method to call is determined dynamically, based on the concrete runtime type of the animal. The only difference is that the OP's animal is an instance of Animal, and yours is an instance of Dog.Sapid
H
1

For non-static functions, you use static binding whenever the function is non-virtual, i.e. the final keyword is applied to it and/or the function is private. final implies the function cannot be changed and the private keyword implies it only has class scope. Otherwise, dynamic binding is used.

For static functions, static binding is always used. If a type A is passed in, it will run A's method, regardless of where A references.

Hemelytron answered 24/3, 2015 at 1:33 Comment(0)
E
0

Case 1:

Animal a =new Animal();
a.eat();

Case 2:

Animal a=new Dog(); 
a.eat();

Here both is dynamic bind because during compile time the type of the object is determined but at runtime based on the instance the object that is assigned the corresponding eat method would be bind dynamically by the JVM .

In the first case the animal class eat method is called whereas in the second the dog class eat is called as the Animal object is assigned an Dog instance.The instance of Dog is also an instance of animal. That is you can take it as "is a" relation a dog is a animal.So here the type of object is determined as dog at runtime and JVM dynamically binds the eat method of the dog class.

Check this links too

http://www.javatpoint.com/static-binding-and-dynamic-binding

http://www.coderanch.com/t/386124/java/java/Static-Binding-Dynamic-Binding

Erle answered 20/5, 2013 at 10:46 Comment(4)
Thanx but can u tell me wht kind of polymorphism my code is exhibiting? Is is static or run time polymorphism?Josselyn
This is plain wrong. It's always the JVM, at runtime, that chooses which overridable method must be called, based on the concrete runtime type of the object. Whether the object is an instance of the declared type or an instance of a subtype doesn't change anything: the binding is dynamic.Sapid
@user2401175 it case 1 it is compile time polymorphism and the case2 : it is runtime check this link i think it answers your question https://mcmap.net/q/23346/-compile-time-polymorphism-vs-run-time-polymorphism/2006839Erle
@JBNizet what i meant by compiler was JVM should have used proper term edited my answer.Erle
L
0

check this employee class has abstract earning() function and each class has deferent toString() implementation

Employee[] employees = new Employee[4];

// initialize array with Employees
employees[0] = new SalariedEmployee();
employees[1] = new HourlyEmployee();
employees[2] = new CommissionEmployee();
employees[3] = new BasePlusCommissionEmployee();
for (Employee currentEmployee : employees){
    System.out.println(currentEmployee); // invokes toString
    System.out.printf("earned $%,.2f%n", currentEmployee.earnings());
}

All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers,

This process is known as dynamic binding or late binding

reference: Java™ How To Program (Early Objects), Tenth Edition

Lordosis answered 31/7, 2017 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.