给定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 PersonIf 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.
更多推荐
发布评论