多态和方法重载 [英] Polymorphism and method overloading

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

问题描述

我有一个快速而直接的问题:

I have a quick and straighforward question:

我有这个简单的课程:

public class A
{
    public void m(Object o)
    {
      System.out.println("m with Object called");
    }

    public void m(Number n)
    {
       System.out.println("m with Number called");
    }
    public static void main(String[] args)
    {
       A a = new A();
       // why will m(Number) be called?
       a.m(null);
    }
}

更新:实际上是实际调用Number的方法.抱歉造成混乱.

UPDATE: actually is method with Number actually being called. Sorry about the confusion.

如果我调用a.m(null),它将使用Number参数调用方法.

If I call a.m(null) it calls method with Number parameter.

我的问题是:为什么?在Java语言规范中的哪个位置?

My question is: why is this? where in the java language specification is this specified?

推荐答案

首先,它实际上调用了m(Number).

First of all, it actually calls m(Number).

之所以会发生这是因为这两种方法都是适用的,但是m(Number)最具体的方法,因为m(Number)的任何参数都可以传递给m(Object),但反之亦然.

It happens because both methods are applicable, but m(Number) is the most specific method, since any argument of m(Number) can be passed to m(Object), but not vice versa.

如果将m(Object)替换为m(String)(或添加其他方法,例如m(Date)),则编译器将报告歧义,因为无法识别出最具体的方法.

If you replace m(Object) by m(String) (or add another method such as m(Date)), compiler would report ambiguity, since the most specific method can't be identified.

请参见Java中的选择最具体的方法规格.

See the section Choosing the Most Specific Method in the Java Specification.

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

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