就Java而言,当有人问:

什么是多态性?

overloadingoverriding是可以接受的答案吗?

我想还有比这更重要的一点.

IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?

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

推荐答案

表达多态性的最清晰方式是通过抽象基类(或接口)

public abstract class Human{
   ...
   public abstract void goPee();
}

This class is abstract because the goPee() method is not definable for Humans. It is only definable for the subclasses Male 和 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.

因此,我们通过使用抽象类来推迟实现.

public class Male extends Human{
...
    @Override
    public void goPee(){
        System.out.println("St和 Up");
    }
}

public class Female extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Sit Down");
    }
}

现在我们可以告诉一整间屋子的人go 小便.

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

运行此命令将产生以下结果:

St和 Up
Sit Down
...

Java相关问答推荐

如何使用Spring Data从MongoDB文档中包含的数组中 Select 单个元素?

在Java中使用带限制的回归打印星形三角形

无法从TemporalAccessor获取Instant:{},ISO解析为2024-04- 25 T14:32:42类型为java.time. form.Parsed

Java Streams在矩阵遍历中的性能影响

如果一个子类没有构造函数,超类也没有构造函数,那么为什么我可以构造子类的实例呢?

在Java Stream上调用collect方法出现意外结果

JavaFX Maven Assembly插件一直打包到错误的JDK版本

嵌入式ActiveMQ Artemis Web控制台加载错误

我找不到&Quot;配置&的位置

如何才能使我的程序不会要求两次输入?

无法了解Java线程所消耗的时间

如何解释Java中for-each循环中对Iterable的强制转换方法引用?

如何使用带有谓词参数的方法,而不使用lambda表达式

我可以在MacOS上使用什么Java函数来在适当的设备上以适当的音量播放适当的alert 声音?

无法在Java中处理PayPal支付响应

使用正则表达式从字符串中提取多个值

如果List是一个抽象接口,那么Collectors.toList()如何处理流呢?

Java.time.OffsetDateTime的SQL Server数据库列类型是什么?

由于版本不匹配,从Java 8迁移到Java 17和Spring 6 JUnit4失败

在数组中查找素数时出现逻辑错误