views:

904

answers:

2

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
+3  A: 

No, the type of value is not available at compile time. Keep in mind that javac will only compile one copy of the code to be used for all possible T's. Given that, the only possible type for the compiler to use in your getValue() method is Object.

C++ is different, because it will eventually create multiple compiled versions of the code as needed.

Darron
Ah... I had thought that Java generics were compiled more like c++ templates. Thanks!
rcreswick
+2  A: 

Because the decision about what makeString() to use is made at compile-time and, based on the fact that T could be anything, must be the Object version. Think about it. If you did Test<String> it would have to call the Object version. As such all instances of Test<T> will use makeString(Object).

Now if you did something like:

public abstract class Test<T extends Integer> {
  ...
}

things might be different.

cletus