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

查看:26
本文介绍了多态 vs 覆盖 vs 重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就Java而言,当有人问:

In terms of Java, when someone asks:

什么是多态?

重载覆盖是可接受的答案吗?

我认为还有更多的东西.

I think there is a bit more to it than that.

如果你有一个抽象基类定义了一个没有实现的方法,并且你在子类中定义了那个方法,那仍然是覆盖的吗?

我认为超载肯定不是正确的答案.

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() 方法不能为人类定义.它只能为子类男性和女性定义.此外,人是一个抽象的概念—你不能创造一个既非男性也非女性的人类.它必须是其中之一.

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天全站免登陆