静态绑定和动态绑定

我对动态绑定和静态绑定感到非常困惑。我已经读到,在编译时确定对象的类型称为静态绑定,在运行时确定它称为动态绑定。

下面的代码中会发生什么情况:

静态绑定还是动态绑定?
这显示了什么样的多态性?

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();
}

答案 1

您的示例是动态绑定,因为在运行时,确定 的类型是什么,并调用相应的方法。a

现在假设您还有以下两种方法:

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

即使您将main

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

这将打印 ,因为调用使用静态绑定,而编译器只知道该类型为 。Animal is eatingcallEataAnimal


答案 2

这实际上取决于重载覆盖,如果你做了这样的事情:

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");
    }
}

然后在主类中:

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

两种情况下的结果将是:Animal is eating

但是让我们扭曲一些,让我们有这个:

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

然后:

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

然后在主类中:

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

现在结果应该是:

Animal is eating
Dog is eating

这是因为重载在编译时绑定“静态绑定”,而在运行时重写绑定“动态绑定”