多态性与重写与重载 [英] Polymorphism vs Overriding vs Overloading

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

问题描述

就Java而言,当有人问:

In terms of Java, when someone asks:


什么是多态?

what is polymorphism?

超载覆盖是否是可接受的答案?

Would overloading or overriding be an acceptable answer?

I认为还有更多的东西。

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");
    }
}

现在我们可以告诉整个房间充满了人类go pee。

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
...

这篇关于多态性与重写与重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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