gpt4 book ai didi

java - 根据参数的真实类型选择重载方法

转载 作者:行者123 更新时间:2023-12-01 17:04:03 25 4
gpt4 key购买 nike

我正在尝试这段代码:

interface Callee {
public void foo(Object o);
public void foo(String s);
public void foo(Integer i);
}

class CalleeImpl implements Callee
public void foo(Object o) {
logger.debug("foo(Object o)");
}

public void foo(String s) {
logger.debug("foo(\"" + s + "\")");
}

public void foo(Integer i) {
logger.debug("foo(" + i + ")");
}
}

Callee callee = new CalleeImpl();

Object i = new Integer(12);
Object s = "foobar";
Object o = new Object();

callee.foo(i);
callee.foo(s);
callee.foo(o);

这会打印 foo(Object o) 三次。我希望方法选择考虑到真实的(而不是声明的)参数类型。我错过了什么吗?有没有办法修改此代码,以便打印 foo(12)foo("foobar")foo(Object o)?

最佳答案

I expect the method selection to take in consideration the real (not the declared) parameter type. Am I missing something?

是的。你的期望是错误的。在 Java 中,动态方法分派(dispatch)仅针对调用该方法的对象,而不针对重载方法的参数类型。

引用Java Language Specification :

When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).

关于java - 根据参数的真实类型选择重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com