Static Binding and Dynamic Binding

后端 未结 6 1479
灰色年华
灰色年华 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:02

    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.

提交回复
热议问题