I ran into a situation today where Java was not invoking the method I expected -- Here is the minimal test case: (I'm sorry this seems contrived -- the 'real world' scenario is substantially more complex, and makes much more sense from a "why the hell would you do that?" standpoint.)
I'm specifically interested in why this happens, I don't care about redesign suggestions. I have a feeling this is in Java Puzzlers, but I don't have my copy handy.
See the specific question in commends within Test<T>.getValue() below:
public class Ol2 {
public static void main(String[] args) {
Test<Integer> t = new Test<Integer>() {
protected Integer value() { return 5; }
};
System.out.println(t.getValue());
}
}
abstract class Test<T> {
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;
}
}
The output from this code is:
obj: 5