静态绑定和动态绑定

Abh*_*nav 30 java oop polymorphism dynamic-binding static-binding

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

以下代码中会发生什么:

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

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();
}
Run Code Online (Sandbox Code Playgroud)

Vin*_*ele 67

您的示例是动态绑定,因为在运行时确定类型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");
}
Run Code Online (Sandbox Code Playgroud)

即使你改变你main

public static void main(String args[])
{
    Animal a = new Dog();
    callEat(a);
}
Run Code Online (Sandbox Code Playgroud)

这将打印Animal is eating,因为调用callEat使用静态绑定,并且编译器只知道它a是类型Animal.

  • 正如Muhammad Ramahy刚刚提到的那样@ user2401175:你*覆盖*类`Animal`的方法`eat`.这使用动态绑定.在我的第二个例子中,I*重载*带有多个签名的`callEat`方法.这使用静态绑定. (5认同)
  • 嗯,你没有说明它真的依赖于覆盖/过载.但很好的答案:-) (2认同)
  • @VincentvanderWeele 那么这是否意味着如果存在方法重载,它将始终是静态绑定,如果存在方法重写,那么绑定将是动态的? (2认同)

Muh*_*ahy 22

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

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在主类:

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

这两个案例的结果将是: Animal is eating

但是让它扭曲一下,让我们这样:

public class Animal{
    public void eat(){
        System.out.println("Animal is eating");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

public class Dog extends Animal{
    public void eat(){
        System.out.println("Dog is eating");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在主类:

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

现在的结果应该是:

Animal is eating
Dog is eating
Run Code Online (Sandbox Code Playgroud)

这是因为重载在编译时绑定"静态绑定",而在运行时覆盖绑定"动态绑定"