我正在阅读一篇有关 Java 面试常见问题的文章,并被一个问题困住了:“多态性的替代方案是什么?”
我搜索过但没有得到任何合理的答案。
Java 中是否有多态性的替代方案?如果是的话,那是什么?
在 Java 中使用多态性的替代方法是使用
instanceof
和类型转换。
这不是好的替代方案...
这是一个例子来说明我的意思:
public interface Animal {
String makeSound(); // polymorphic method ...
}
public class Cat implements Animal {
public String makeSound() { return "meow"; }
}
public class Dog implements Animal {
public String makeSound() { return "woof"; }
}
// polymorphic:
Animal someAnimal = ...
System.out.println("Animal sound is " + someAnimal.makeSound());
// non-polymorphic
if (someAnimal instanceof Cat) {
System.out.println("Animal sound is " + ((Cat) someAnimal).makeSound());
} else if (someAnimal instanceof Dog) {
System.out.println("Animal sound is " + ((Dog) someAnimal).makeSound());
}
请注意,非多态版本显然更加冗长。但问题是,如果
Cat
和 Dog
没有带有 makeSound()
方法的通用接口,非多态版本也可以工作。
这可能是面向对象编程的一条规则,称为组合优于继承, 它指出对象应该通过包含实现所需功能的其他类的实例来实现多态行为,而不是通过从父类继承来实现。