多态性 vs 覆盖 vs 重载 [英] Polymorphism vs Overriding vs Overloading

查看:24
本文介绍了多态性 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 重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆