我今天遇到了一种情况,其中Java没有调用我期望的方法-
这是最小的测试用例:(很抱歉,这似乎是人为设计的-“现实世界”场景要复杂得多,并且更有意义从“究竟为什么会怎么做 那 ?”的立场。)
我对为什么会发生这种情况特别感兴趣,我不在乎重新设计的建议。我觉得这是Java Puzzlers中的功能,但是我没有副本。
请参见下面的Test .getValue()中的特定建议问题:
public class Ol2 {
public static void main(String[] args) {
Test t = new Test() {
protected Integer value() { return 5; }
};
System.out.println(t.getValue());
}
}
abstract class Test {
protected abstract T value();
public String getValue() {
// Why does this always invoke makeString(Object)?
// The type of value() is available at compile-time.
return Util.makeString(value());
}
}
class Util {
public static String makeString(Integer i){
return "int: "+i;
}
public static String makeString(Object o){
return "obj: "+o;
}
}
此代码的输出是:
obj: 5