Java中具有重载方法的类型顺序 [英] Type order with overloaded methods in Java

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

问题描述

在Java的同一类上给出两个方法:

Given two methods on the same class in Java :

public void doSomething( Person person );
public void doSomething( Employee employee );

其中

Employee extends Person

如果我打电话:

doSomething( employee )

我发现 doSomething(Person)被调用.

我希望调用最接近的匹配协定的重载,而不是最抽象的(这就是我所发现的)

I'd have expected the overload with the closest matching contract be invoked, not with the most abstract (which is what I'm finding)

有人可以解释为什么吗?

Could someone explain why?

推荐答案

使用了最具体的适用重载-但该重载是在 compile 时根据编译时类型确定的. employee 变量.

The most specific applicable overload is used - but that overload is determined at compile-time, based on the compile time type of the employee variable.

换句话说:

Employee employee = new Employee();
doSomething(employee); // Calls doSomething(Employee)

但是:

Person employee = new Employee();
doSomething(employee); // Calls doSomething(Person)

请注意,这与 overrideing 不同,在后者中,重要的是目标对象的执行时间类型.

Note that this is unlike overriding where it's the execution time type of the target object which is important.

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

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