Static Binding and Dynamic Binding

后端 未结 6 1506
灰色年华
灰色年华 2020-11-27 13:46

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

6条回答
  •  醉酒成梦
    2020-11-27 14:05

    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.

提交回复
热议问题