我正在阅读一篇有关 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()
方法的公共(public)接口(interface),非多态版本将起作用.
关于java - Java 中除了多态性还有其他选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52342325/