Java中的静态绑定和动态绑定问题

Dun*_*Dev 6 java oop runtime compilation

我已经阅读了一些关于Java中的静态绑定动态绑定的文章.我有以下问题(我已经搜索了很多,但没有找到任何关于它的提及):

例如,我有以下几行代码:

Person a = new Student(); // Student is a subclass of Person
a.speak();
Run Code Online (Sandbox Code Playgroud)

我们已经知道的是,在编译时,编译器会检查是否存在方法定义为speak()Person,如果它存在调用它.并且在运行时,它将调用speak()的实际对象的方法,其a指向(在这种情况下,实际的目的是清楚Student)

所以我的问题是为什么它不能在编译时直接调用speak()类的方法,而是等到运行时才这样做?这背后有什么理由吗?Student

Sup*_*ghe 5

代码编译时,有时并不清楚需要调用哪个方法,只能在运行时确定。

以这个简单的代码为例。

class Animal{   

    public void makeNoise(){
       System.out.println("Default");
    };
}

class Dog extends Animal{

    //override the makeNoise()
    public void makeNoise(){
        System.out.println("Woof");
    };
}

class Cat extends Animal{

        //override the makeNoise()
        public void makeNoise(){
            System.out.println("Meow");
        };
    } 

public class Sounds{

    public static void AnimalSounds(Animal animal){
    animal.makeNoise();
    }

    public static void main(String args[]){

        Animal dog = new Dog();     
        Animal cat = new Cat(); 
        AnimalSounds(dog);
        AnimalSounds(cat);  
    }
}
Run Code Online (Sandbox Code Playgroud)

AnimalSounds(Animal animal)方法接受任何通过ISAAnimal 测试的对象并调用该对象的相应方法。正如您所看到的,它也消除了代码重复,因为我们可以对不同类型的对象使用相同的方法。

希望这能解决您的担忧。