使用Java中的重载方法键入顺序(Type order with overloaded methods in Java)

编程入门 行业动态 更新时间:2024-10-22 14:42:43
使用Java中的重载方法键入顺序(Type order with overloaded methods in Java)

给定Java中相同类的两种方法:

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

哪里

Employee extends Person

如果我打电话给:

doSomething( employee )

我发现doSomething(Person)被调用。

我曾预料过,与最接近的匹配合约被调用,而不是最抽象的(这正是我所发现的)

有人能解释为什么吗?

问候

马蒂

Given two methods on the same class in Java :

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

where

Employee extends Person

If I call:

doSomething( employee )

I find that doSomething( Person ) gets invoked.

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?

最满意答案

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

换一种说法:

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

但:

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

请注意,这与重写目标对象的执行时间类型非常重要。

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.

In other words:

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

but:

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

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

更多推荐

本文发布于:2023-07-31 02:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   方法   Java   Type   methods

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!