java - 基于参数真实类型的重载方法选择

标签 java oop

我正在试验这段代码:

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/1572322/

相关文章:

java - 无法实现 Parcelable,因为我无法将 CREATOR 字段设为静态

c# - 单击后更改按钮文本,然后再次单击后将其更改回

c++ - 使用运算符重载表格

oop - 派生一个类只是为了识别类型是个好主意吗?

javascript - 使用 this 从嵌套函数内部获取值

oop - 将 RInside 的 'R' 实例作为类/方法之间的参数传递

java - 用于 java swing 应用程序的开源 laf[外观]

java - java中多维字符串数组的连接

java - JSP 无法解析 org.apache.commons.lang 的导入

java - 从 Android 中的 AlertDialog 选择/拍照