MST

星途 面试题库

面试题:Java多态中编译器选择重载方法的依据

在Java多态的场景下,编译器在选择重载方法时主要依据哪些因素?请结合具体代码示例说明。
48.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 依据因素
    • 参数的数量:方法重载时,不同重载方法的参数数量可以不同。
    • 参数的类型:参数类型不同,也可以构成方法重载。参数类型的顺序不同同样可以构成方法重载。
  2. 代码示例
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Cat meows");
    }
}

class AnimalSoundUtil {
    // 参数数量不同的重载方法
    static void makeSound(Animal animal) {
        animal.makeSound();
    }

    static void makeSound(Animal animal1, Animal animal2) {
        animal1.makeSound();
        animal2.makeSound();
    }

    // 参数类型不同的重载方法
    static void makeSound(int num) {
        System.out.println("Number of animals: " + num);
    }

    // 参数类型顺序不同的重载方法
    static void makeSound(Animal animal, int num) {
        System.out.println("For " + num + " ");
        animal.makeSound();
    }

    static void makeSound(int num, Animal animal) {
        System.out.println("There are " + num + " ");
        animal.makeSound();
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();

        AnimalSoundUtil.makeSound(dog);
        AnimalSoundUtil.makeSound(dog, cat);
        AnimalSoundUtil.makeSound(2);
        AnimalSoundUtil.makeSound(dog, 1);
        AnimalSoundUtil.makeSound(1, dog);
    }
}

在上述代码中,AnimalSoundUtil类中有多个makeSound方法,它们通过不同的参数数量、参数类型以及参数类型顺序构成了方法重载。在调用这些方法时,编译器会根据传入参数的具体情况选择合适的重载方法。例如AnimalSoundUtil.makeSound(dog)会调用参数为Animal类型的makeSound方法,而AnimalSoundUtil.makeSound(2)会调用参数为int类型的makeSound方法。