Polymorphism vs Overriding vs Overloading(多态性 vs 覆盖 vs 重载)
问题描述
在Java方面,当有人问:
In terms of Java, when someone asks:
什么是多态性?
重载或覆盖是可接受的答案吗?
我认为还有更多.
如果你有一个抽象基类,它定义了一个没有实现的方法,而你在子类中定义了那个方法,那仍然是覆盖吗?
我认为重载肯定不是正确的答案.
I think overloading is not the right answer for sure.
推荐答案
表达多态性最清晰的方式是通过抽象基类(或接口)
The clearest way to express polymorphism is via an abstract base class (or interface)
public abstract class Human{
...
public abstract void goPee();
}
这个类是抽象的,因为 goPee() 方法对于人类来说是不可定义的.它只能为子类 Male 和 Female 定义.此外,人是一个抽象的概念——你不能创造一个既不是男性也不是女性的人.必须是其中之一.
This class is abstract because the goPee() method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept — You cannot create a human that is neither Male nor Female. It’s got to be one or the other.
所以我们使用抽象类来推迟实现.
So we defer the implementation by using the abstract class.
public class Male extends Human{
...
@Override
public void goPee(){
System.out.println("Stand Up");
}
}
和
public class Female extends Human{
...
@Override
public void goPee(){
System.out.println("Sit Down");
}
}
现在我们可以让满屋子的人去小便.
Now we can tell an entire room full of Humans to go pee.
public static void main(String[] args){
ArrayList<Human> group = new ArrayList<Human>();
group.add(new Male());
group.add(new Female());
// ... add more...
// tell the class to take a pee break
for (Human person : group) person.goPee();
}
运行它会产生:
Stand Up
Sit Down
...
这篇关于多态性 vs 覆盖 vs 重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多态性 vs 覆盖 vs 重载
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
